冒泡排序:
基本:
private static void sort(int[] a){for (int i = 0; i < a.length-1; i++) {for (int j = 0; j < a.length-i-1; j++) {if (a[j]>a[j+1]){swap(a,j,j+1);}}}}
private static void swap(int[] a,int i,int j){int temp=a[i];a[i]=a[j];a[j]=temp;}
优化一:
private static void sort2(int[] a){for (int i = 0; i < a.length-1; i++) {boolean swapped=false;for (int j = 0; j < a.length-i-1; j++) {if (a[j]>a[j+1]){swap(a,j,j+1);swapped=true;}}if (!swapped){break;}}}
private static void swap(int[] a,int i,int j){int temp=a[i];a[i]=a[j];a[j]=temp;}
优化二:
private static void sort1(int[] a){int n=a.length-1;while (true){int last=0;for (int j = 0; j <n; j++) {if (a[j]>a[j+1]){swap(a,j,j+1);last=j;}}n=last;if (n==0){break;}}}private static void swap(int[] a,int i,int j){int temp=a[i];a[i]=a[j];a[j]=temp;}
选择排序:
将数组划分为有序和无序,每一轮都选择一个最小的值加入到已排序部分。
private static void sort1(int[] a){for (int i = 0; i < a.length; i++) {int minIndex=i;for (int j = i+1; j <a.length; j++) {if (a[minIndex]>a[j]){minIndex=j;}}if (minIndex!=i){swap(a,minIndex,i);}}}private static void swap(int[] a,int i,int j){int temp=a[i];a[i]=a[j];a[j]=temp;}