Java学习:冒泡排序和选择排序

冒泡排序

基本概念:相邻的两个元素进行比较,小的放前面,大的放后面

 1 public class StringSortDemo {
 2     public static void main(String[] args) {
 3         //使用冒泡排序
 4         String s = "dacgebf";
 5         //转换成字符数组
 6         char[] chs = s.toCharArray();
 7         /*//使用冒泡排序对字符根据ascii码表进行排序
 8         for (int i = 0; i < chs.length-1; i++) {
 9             for (int j = 0; j < chs.length-1-i; j++) {
10                 if (chs[j]>chs[j+1]) {
11                     char temp = chs[j];
12                     chs[j] = chs[j+1];
13                     chs[j+1] = temp;
14                 }
15             }
16         }*/
17         
18         //使用Arrays里面的sort()方法给字符数组进行排序
19         Arrays.sort(chs);
20         //打印数组
21         System.out.println(Arrays.toString(chs));
22         
23     }
24 
25 }

选择排序

 基本概念

从0索引开始,依次和后面的每一个元素进行比较
* 第一次比较完毕,最小值出现在了最小索引处
* 第二次比较完毕,次小值出现在了次小索引处
* ...
* 完毕后,就排序了。

原文地址:https://www.cnblogs.com/shaofanglazi/p/6705325.html