毕业季在即,一大波面试接踵而来,为了一份好offer,所以最近在重新刷数据结构与算法。正好在博客里面记录一下。今天是归并排序的实现。 归并排序是典型的分治模式的实现,对一个数组A,采取三步实现:分解,解决,合并 分解:分解待排序的n个元素的序列成各
java实现的归并排序算法, 非常清晰,希望分享出来共同交流学习! public class MergeSort{
public static void main(String args[]){
int []a = {1,8,9,7,5,4,5,1,2,4,5,78,2};
mergeSort(a);
for(int i:a){
System.out.print(i+",");
}
}
public mergeSort(int[]a){
sort(a,0,a.length-1);
}
public static void sort(int []a,int L ,int R){
if(L
int M = (L+R)/2;
sort(a,L,M);
sort(a,M+1,R);
merge(a,L,M,R);
}
}
public static void merge(int[]a,int L,int M,int R){
if(L
int start1=L;
int end1=M;
int start2=M+1;
归并排序的核心:两个有序子列的归并 (图片来自 中国大学MOOC《数据结构》) 如上所示,假如我们已经有了这样两个有序的子序列,首先要做的就是把这两个子列合并。为此,可以开另外一个数组,然后把这几个数字按照一定次序放进去,保证最后那个数组是从小到
int end2=R;
int [] temp = new int [R-L+1];
int index = 0;
int i=start1;
int j=start2;
while(i<=end1&&j<=end2){
if(a[i]>=a[j]){
temp[index++]=a[i++];
}
else{
temp[index++]=a[j++];
}
}
while(i<=end1){
temp[index++]=a[i++];
}
while(j<=end2){
temp[index++]=a[j++];
}
for(index=0;index
a[L+index]=temp[index];
}
}
}}