归并排序是分治(Divide and conquer)思想的典型应用,该算法利用递归方法将无序数组分割成左右两个子数组,并对子数组进行排序,然后将排好序的子数组合并,从而得到整个有序的数组
归并排序的时间复杂度: O(nlogn)
可以参见以下例子:
从上图可以看出,我们首先把一个未排序的序列从中间分割成2部分,再把2部分分成4部分,依次分割下去,直到分割成一个一个的数据,再把这些数据两两归并到一起,使之有序,不停的归并,最后成为一个排好序的序列。
Java Code:
package Sort;
public class MergeSort {
public static void MergeSortAlgorithm(float flt[], int length){
int first=0, last=length-1;
RecursiveSort(flt, first, last);
}
private static void RecursiveSort(float[] flt, int first, int last){
if (first<last) {//Divide and conquer: divide until one element in the array
int mid=(first+last)/2;//Divide array in the middle
RecursiveSort(flt, first, mid);
RecursiveSort(flt, mid+1, last);
MergeSubSort(flt, first, mid, last);
}
}
private static void MergeSubSort(float[] flt, int start, int mid, int end){
float[] sortedSubArray=new float[end-start+1];//Extra space to store the sorted sub-array
int i=start, j=mid+1, k=0;//Three cursors for two sub-arrays and one merge-array
while(i<mid+1&&j<end+1){
if (flt[i]<flt[j]) {
sortedSubArray[k]=flt[i];
i++;
}
else {
sortedSubArray[k]=flt[j];
j++;
}
k++;
}
//Either one sub-array is empty, the extra part of other sub-array will be put into the merge-array completely
while(i>=mid+1&&j<end+1){
sortedSubArray[k++]=flt[j++];
}
while (j>=end+1&&i<mid+1) {
sortedSubArray[k++]=flt[i++];
}
//Reflect the modification in the source array
for(int x=start, y=0;x<end+1;x++,y++){
flt[x]=sortedSubArray[y];
}
}
}
参考:
http://www.cnblogs.com/FlyingBread/archive/2007/02/02/636990.html
http://blog.csdn.net/morewindows/article/details/6678165