排序
1.冒泡排序
关键词:两两比较
1 public static void sort(int[] a){ 2 int temp = 0; 3 for(int i=a.length-1;i>0;i--){ 4 for(int j=0;j<i;j++){ 5 if(a[j]>a[j+1]){ 6 temp = a[j]; 7 a[j] = a[j+1]; 8 a[j+1] = temp; 9 } 10 } 11 } 12 }
通过逐一比较相邻两个数的大小,并将较大数放在较小数之后(反之亦然),第一轮过后最大(小)的数将在最后,以此类推。
2.选择排序
关键词:选取最小(大)数
1 public static void selectSort(int[] a){ 2 int temp = 0; 3 for(int i=0;i<a.length;i++){ 4 for(int j=i+1;j<a.length;j++){ 5 if(a[i]>a[j]){ 6 temp = a[i]; 7 a[i] = a[j]; 8 a[j] = temp; 9 } 10 } 11 } 12 }
选取最小(大)数放于起始位置,再从剩余元素中寻找最小(大)数。第一轮,将第一个数依次与其他元素比较大小,将较小者放入第一个元素位子(互换位置),即第一轮找出了最小元素并置于起始位置,第二轮则找出第2小的元素置于第2个位置。以此类推
3.插入排序
关键词:左侧元素已排好序
1 /** 2 * 插入排序 3 * @param a 4 */ 5 public static void insertSort(int[] a){ 6 for(int i=1;i<a.length;i++){ 7 for(int j=i;(j>0)&&(a[j]<a[j-1]);j--){ 8 swap(a, j, j-1); 9 } 10 } 11 } 12 /** 13 * 交换 14 * @param a 15 * @param i 16 * @param j 17 */ 18 public static void swap(int[] a,int i,int j){ 19 int temp = 0; 20 temp = a[i]; 21 a[i] = a[j]; 22 a[j] = temp; 23 }
插入排序算法有种递归的思想在里面,它由N-1趟排序组成。初始时,只考虑数组下标0处的元素,只有一个元素,显然是有序的。
然后第一趟 对下标 1 处的元素进行排序,保证数组[0,1]上的元素有序;
第二趟 对下标 2 处的元素进行排序,保证数组[0,2]上的元素有序;
.....
.....
第N-1趟对下标 N-1 处的元素进行排序,保证数组[0,N-1]上的元素有序,也就是整个数组有序了。
它的递归思想就体现在:当对位置 i 处的元素进行排序时,[0,i-1]上的元素一定是已经有序的了。
4.快速排序
关键 ;大的问题分割为更小的问题
1 /** 2 * 一轮排序,基准点左侧的元素都小于基准点,右侧的元素都大于基准点 3 * @param a 4 * @param low 5 * @param high 6 * @return 7 */ 8 public static int partition(int[] a,int low ,int high){ 9 int key = a[low];//基准点 10 11 while(low<high){ 12 //从后向前扫描 13 while(a[high]>=key&&high>low){ 14 high--; 15 } 16 a[low]=a[high]; 17 //从前向后扫描 18 while(a[low]<=key && high>low){ 19 low++; 20 } 21 a[high] = a[low]; 22 } 23 a[high] = key; 24 return high; 25 } 26 27 /** 28 * 递归 29 * @param a 30 * @param low 31 * @param high 32 */ 33 public static void quickSort(int[] a,int low,int high){ 34 if(low>high){ 35 return; 36 } 37 //分割点 38 int index = partition(a, low, high); 39 //左侧排序 40 quickSort(a, low, index-1); 41 //右侧排序 42 quickSort(a, index+1, high); 43 }
选取一个基准点(例子中以下标为low的元素作为基准点),让基准点左侧元素都小于基准点,右侧元素都大于基准点,在将左侧元素作为一个数组进行相同操作(右侧相同)。
5.归并排序
关键:已经排序的两个序列合并为一个序列
1 /** 2 * 归并排序 3 * @param a 4 * @param low 5 * @param high 6 */ 7 public static void mergeSort(int[] a,int low,int high){ 8 int mid = (low+high)/2; 9 if(low<high){ 10 mergeSort(a, low, mid); 11 mergeSort(a, mid+1, high); 12 merge(a, low, mid, high); 13 } 14 } 15 16 /** 17 * 归并,将两个有序列 合并为一个有序列 18 * @param a 19 * @param low 20 * @param mid 21 * @param high 22 */ 23 public static void merge(int[] a,int low,int mid,int high){ 24 int[] temp = new int[high-low+1];//归并后的序列 25 int i = low,j=mid+1,k=0; 26 //将较小的数依次放入temp中 27 while(i<=mid&&j<=high){ 28 if(a[i]<a[j]){ 29 temp[k++] = a[i++]; 30 }else{ 31 temp[k++] = a[j++]; 32 } 33 } 34 //将剩余数放入temp 35 while(i<=mid){ 36 temp[k++]=a[i++]; 37 } 38 while(j<=high){ 39 temp[k++]=a[j++]; 40 } 41 //覆盖a 42 for(int x=0;x<temp.length;x++){ 43 a[low+x] = temp[x]; 44 } 45 }
将序列分割为单个元素,再两两归并。