冒泡排序-----基础排序算法
1 public class maopao { 2 public static void main(String[] args) { 3 int[] arr={123,4,8,6,3,7,8,9,10,45,89,57,45,75,26,78}; 4 for (int i = 1; i <arr.length-1; i++) { 5 for (int j=0;j<arr.length-i;j++){ 6 if (arr[j]>arr[j+1]){ 7 int temp=arr[j]; 8 arr[j]=arr[j+1]; 9 arr[j+1]=temp; 10 } 11 } 12 } 13 for (int i = 0; i < arr.length; i++) { 14 System.out.print(arr[i]+","); 15 } 16 } 17 }
运行结果:3,4,6,7,8,8,9,10,26,45,45,57,75,78,89,123,
每次循环,找出最大值,下一次可以少循环一次
选择排序------与冒泡排序原理基本相同
1 public class xuanze { 2 public static void main(String[] args) { 3 int[] arr ={1,8,56,7,78,89,64,7,5,3,4,98}; 4 for (int i = 0; i < arr.length; i++) { 5 for(int j=i+1;j<arr.length;j++){ 6 int max =arr[i]; 7 if (arr[j]<max){ 8 int temp; 9 temp=arr[i]; 10 arr[i]=arr[j]; 11 arr[j]=temp; 12 } 13 } 14 } 15 System.out.println(Arrays.toString(arr)); 16 17 } 18 }
运行结果:[1, 3, 4, 5, 7, 7, 8, 56, 64, 78, 89, 98]
此处优化数组循环遍历改为Arrats.ToString.sout--->回车快捷键遍历数组更方便
插入排序
插入排序思想:数组从第i位开始,向前遍历使前方数组保持有序,直到数组遍历结束,数组变为有序数组
1 public class charu { 2 public static void main(String[] args) { 3 int[] arr={5,6,9,7,12,54,68,78,49,15,75,58,15,75}; 4 for (int i = 1; i < arr.length; i++) { 5 for (int j = i; j >0 ; j--) { 6 if (arr[j]<arr[j-1]){ 7 swap(arr,j,j-1); 8 } 9 } 10 } 11 //数组遍历循环优化,减少代码 12 System.out.println(Arrays.toString(arr)); 13 } 14 //交换代码,简化直接调用 15 public static void swap(int[] arr,int i, int j){ 16 int t=arr[i]; 17 arr[i]=arr[j]; 18 arr[j]=t; 19 } 20 }
输出结果:[5, 6, 7, 9, 12, 15, 15, 49, 54, 58, 68, 75, 75, 78]
希尔排序------>缩小增量排序
1 public class xier { 2 public static void main(String[] args) { 3 int[] arr={2,5,8,7,9,78,18,35,48,62,58}; 4 xiE(arr); 5 } 6 public static void xiE(int[] arr){ 7 int leagth=0; 8 while(leagth<(arr.length)/3){ 9 leagth=(leagth*3)+1; 10 System.out.println(leagth); 11 } 12 for (int h = leagth; h >0; h=(h-1)/3) { 13 for (int i = h; i <arr.length ; i++) { 14 for (int j = i; j >h-1 ; j-=h) { 15 if (arr[j]<arr[j-h]){ 16 swap(arr,j,j-h); 17 } 18 } 19 } 20 } 21 System.out.println(Arrays.toString(arr)); 22 } 23 public static void swap(int[] arr,int i,int j){ 24 int t=arr[i]; 25 arr[i]=arr[j]; 26 arr[j]=t; 27 } 28 }
运行结果:[2, 5, 7, 8, 9, 18, 35, 48, 58, 62, 78]
通过增量不断变小,数组逐渐变得有序,增量为一是原理与插入排序一样