归并排序 (Merge Sort)

归并排序是分治(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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值