算法导论–第二章 merge sort java代码实现
public class Sort {
public static void main(String[] args){
int[] arr = new int[]{8,30,19,1,45,3,6};
System.out.println("before sort: ");
printarr(arr);
mergesort(arr,0,arr.length-1);
System.out.println("merge sort result: ");
printarr(arr);
System.out.println();
}
//归并排序
//采用分治的思想,递归调用,分成两份,每份各自排序,然后再合并结果;合并时采用三个指针
private static void mergesort(int[] arr,int start,int end) {
if(end>start){
int divide = (start+end)/2;
mergesort(arr,start,divide);
mergesort(arr,divide+1,end);
merge(arr,start,end,divide);
}
}
private static void merge(int[] arr,int start,int end,int divide) {
//三个指针的初始化
int i = 0;
int j = 0;
int k = start;
//创建左右子数组,并赋值
int lsize = divide-start+1;
int rsize = end-divide;
int[] arrL = new int[lsize];
int[] arrR = new int[rsize];
for(int n =0;n<lsize;n++){
arrL[n] = arr[n+start];
}
for(int n =0;n<rsize;n++){
arrR[n] = arr[n+divide+1];
}
//三个指针移动,进行合并
while(i<lsize&&j<rsize){
if(arrL[i]<arrR[j]){
arr[k]=arrL[i];
k++;
i++;
}else{
arr[k]=arrR[j];
k++;
j++;
}
}
//把剩余的都填进arr
while(i<lsize){
arr[k]=arrL[i];
k++;
i++;
}
while(j<rsize){
arr[k]=arrR[j];
k++;
j++;
}
System.out.print(" 本次递归的结果:");
printarr(arr);
}
public static void printarr(int[] arr){
for(int i = 0;i<arr.length;i++){
if(i!=arr.length-1){
System.out.print(arr[i]+",");
}else{
System.out.print(arr[i]);
System.out.println();
}
}
}
}
运行结果:
before sort:
8,30,19,1,45,3,6
本次递归的结果:8,30,19,1,45,3,6
本次递归的结果:8,30,1,19,45,3,6
本次递归的结果:1,8,19,30,45,3,6
本次递归的结果:1,8,19,30,3,45,6
本次递归的结果:1,8,19,30,3,6,45
本次递归的结果:1,3,6,8,19,30,45
merge sort result:
1,3,6,8,19,30,45