一、归并排序
思路:首先将待排序列进行递归划分区间,直到区间长度为1,然后左右归并成有序序列
例如:
待排序列 | 51 | 46 | 20 | 18 | 95 | 67 | 82 | 30 |
---|---|---|---|---|---|---|---|---|
第1轮 | 46 | 51 | 20 | 18 | 95 | 67 | 82 | 30 |
第2轮 | 46 | 51 | 18 | 20 | 95 | 67 | 82 | 30 |
第3轮 | 18 | 20 | 46 | 51 | 95 | 67 | 82 | 30 |
第4轮 | 18 | 20 | 46 | 51 | 67 | 95 | 82 | 30 |
第5轮 | 18 | 20 | 46 | 51 | 67 | 95 | 30 | 82 |
第6轮 | 18 | 20 | 46 | 51 | 30 | 67 | 82 | 95 |
第7轮 | 18 | 20 | 30 | 46 | 51 | 67 | 82 | 95 |
程序代码:
import java.util.Arrays;
public class SortTest1 {
public static void main(String[] args) {
int[] a = {51,46,20,18,95,67,82,30};
mergeSort(a, 0, a.length-1);
System.out.println(Arrays.toString(a));
}
//待排序的数组和要排序的范围
public static void mergeSort(int[] a,int low,int high) {
int mid = (low+high)/2;
if(low<high) {
mergeSort(a, low, mid);
mergeSort(a, mid+1, high);
merge(a,low,mid,high);
}
}
public static void merge(int[] a,int low,int mid,int high) {
int[] tmp = new int[high-low+1];//临时数组的长度,用来归并
int i=low,j=mid+1,k=0;
while(i<=mid && j<=high) {
if(a[i]<a[j]) {
tmp[k] = a[i];
k++;
i++;
} else {
tmp[k] = a[j];
k++;
j++;
}
}
while(i<=mid) {
tmp[k] = a[i];
k++;
i++;
}
while(j<=high) {
tmp[k] = a[j];
k++;
j++;
}
for(int index=0;index<tmp.length;index++) {
a[low+index] = tmp[index];
}
}
}
二、快速排序
例如:
待排序列 | 49 | 38 | 65 | 97 | 76 | 13 | 27 | 49* |
---|---|---|---|---|---|---|---|---|
第1轮 | 27 | 38 | 13 | 49 | 76 | 97 | 65 | 49* |
第2轮 | 13 | 27 | 38 | 49 | 49* | 65 | 76 | 97 |
第3轮 | 13 | 27 | 38 | 49 | 49* | 65 | 76 | 97 |
程序代码:
import java.util.Arrays;
public class SortTest2 {
public static void main(String[] args) {
int[] a = {49,38,65,97,76,13,27,49};
quickSort(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}
public static void quickSort(int[] a, int low, int high) {
if(low>high) return ;
int i=low,j=high,tmp=a[low];//a[low]作为基准点
while(i!=j) {
while(a[j]>=tmp && j>i) j--;//只要a[j]大于基准点,继续往前移动j
if(j>i) {
a[i]=a[j];
i++;
}
while(a[i]<=tmp && i<j) i++;//只要a[i]小于基准点,继续往后移动i
if(i<j) {
a[j]=a[i];
j--;
}
}
a[i] = tmp;//基准点放入最终的位置
quickSort(a,low,i-1);
quickSort(a,i+1,high);
}
}