您的位置:首页 > 编程语言 > Go语言

Algorithm 101----merge sort

2014-05-13 20:18 316 查看
Although I met this topic quite a long ago, I never did such a solid thing---- write a piece of merge-sort code with my own hands! Really thanks the MOOC course "Algorithm part1" offered by Standford, I was motivated again to have a hands-on experience in
this topic ! 

First of all, let me remember how merge-sort works. Naturally people would implement this by using the divide-conquer strategy.

First of all, let me say what a merge step is:

Given two input array a[] and b[],

then combine the two arrays into a larger one c[], here is the psuedocode for merge step. 

for  i=1:1:length(c)

if a[j]>b[k]

c[i]=b[k];

k++

else

c[i]=a[j];

j++

end 

During the implementation, we divide the whole problem into the smallest problems, each  with a size 1, then merge the smallest problems into a bigger sorted one, then merger the bigger ones into further bigger ones, repeat this process again and again until
we arrive the original problem. 

here is the full-version psuedocode for merge sort:

function mergesort ( intput  array)

 if intput array's size==1

then return input array 

else 

 temp array1=mergesort( the first half of input array);

temp array2= mergesort(the second half of input array);

return   merge(temp array 1,  temp array 2);

remember each merge process's cost is 6*input size. the cost of merge sort is O(nlogn). it beats most of sorting algorithm off the shelves ! 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: