1.选择排序法:
思路:
把第一位和其他所有的进行比较,只要比第一位小的,就换到第一个位置来
比较完后,第一位就是最小的
然后再从第二位和剩余的其他所有进行比较,只要比第二位小,就换到第二个位置来
比较完后,第二位就是第二小的 ,以此内推。
1 public class SelectionSort { 2 public static void main(String[] args) { 3 int[] a = new int[] {18,62,68,65,9}; 4 //排序前先把内容打印出来 5 for (int i = 0; i < a.length; i++) { 6 System.out.print(a[i]+" "); 7 } 8 System.out.println(); 9 System.out.println("------------------------------------------"); 10 //选择排序 11 //第一步:把第一位和其他所以位进行比较,如果发现其他位置的数比第一位小,就交换数值 12 for (int i = 1; i < a.length; i++) { 13 if (a[0]>a[i]) { 14 int temp = a[0]; 15 a[0] = a[i]; 16 a[i] = temp; 17 } 18 } 19 //把内容打印出来,可以发现,最小的一个数,到了最前面 20 for (int i = 0; i < a.length; i++) { 21 System.out.print(a[i]+" "); 22 } 23 System.out.println(); 24 System.out.println("------------------------------------------"); 25 26 //第二步: 把第二位的和剩下的所有位进行比较 27 for (int i = 2; i < a.length; i++) { 28 if (a[1]>a[i]) { 29 int temp = a[1]; 30 a[1] = a[i]; 31 a[i] = temp; 32 } 33 } 34 for (int i = 0; i < a.length; i++) { 35 System.out.print(a[i]+" "); 36 } 37 //把内容打印出来,可以发现,倒数第二小的数,到了第二个位置 38 System.out.println(); 39 System.out.println("------------------------------------------"); 40 //可以发现一个规律 41 //移动的位置是从0 逐渐增加的 42 //所以可以在外面套一层循环 43 for (int i = 0; i < a.length-1; i++) { 44 for (int j = i+1; j < a.length; j++) { 45 if (a[i]>a[j]) { 46 int temp = a[i]; 47 a[i] = a[j]; 48 a[j] = temp; 49 } 50 } 51 } 52 //把内容打印出来 53 for (int i = 0; i < a.length; i++) { 54 System.out.print(a[i]+" "); 55 } 56 } 57 }
2.冒泡排序
思路:
第一步:从第一位开始,把相邻两位进行比较
如果发现前面的比后面的大,就把大的数据交换在后面,循环比较完毕后,最后一位就是最大的
第二步: 再来一次,只不过不用比较最后一位
以此类推
1 public class BubbleSort { 2 3 public static void main(String[] args) { 4 int[] a = new int[] { 18, 62, 68, 82, 65, 9 }; 5 // 排序前,先把内容打印出来 6 for (int i = 0; i < a.length; i++) { 7 System.out.print(a[i] + " "); 8 } 9 System.out.println(); 10 System.out.println("----------------"); 11 // 冒泡排序 12 // 第一步:从第一位开始,把相邻两位进行比较 13 // 如果发现前面的比后面的大,就把大的数据交换在后面 14 for (int i = 0; i < a.length - 1; i++) { 15 if (a[i] > a[i + 1]) { 16 int temp = a[i]; 17 a[i] = a[i + 1]; 18 a[i + 1] = temp; 19 } 20 } 21 // 把内容打印出来 22 // 可以发现,最大的到了最后面 23 for (int i = 0; i < a.length; i++) { 24 System.out.print(a[i] + " "); 25 } 26 System.out.println(); 27 System.out.println("----------------"); 28 // 第二步: 再来一次,只不过不用比较最后一位 29 for (int i = 0; i < a.length - 2; i++) { 30 if (a[i] > a[i + 1]) { 31 int temp = a[i]; 32 a[i] = a[i + 1]; 33 a[i + 1] = temp; 34 } 35 36 } 37 // 把内容打印出来 38 // 可以发现,第二大的数的到了倒数第二个位置 39 for (int i = 0; i < a.length; i++) { 40 System.out.print(a[i] + " "); 41 } 42 System.out.println(); 43 System.out.println("----------------"); 44 // 可以发现一个规律 45 // 后边界在收缩 46 // 所以可以在外面套一层循环 47 for (int j = 0; j < a.length; j++) { 48 for (int i = 0; i < a.length - j - 1; i++) { 49 if (a[i] > a[i + 1]) { 50 int temp = a[i]; 51 a[i] = a[i + 1]; 52 a[i + 1] = temp; 53 } 54 } 55 } 56 // 把内容打印出来 57 for (int i = 0; i < a.length; i++) { 58 System.out.print(a[i] + " "); 59 } 60 61 } 62 }