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

Algorithm_2_Merge_Sort

2008-03-04 19:48 417 查看
In the card-playing motif,suppose we have two piles of cards face up on a table.Each pile is sorted,with the smallest cards on top.We wish to merge the two piles into a single sorted output pile,which is to be face down on the table.Our basic step consists of choosing the smaller of the two cards on top of of the face_up piles,removing it from its pile(which expsoe a new top card),and placing this card face down onto the output pile.We repeat this step until one input pile is empty,at which time we just take the remaining input pile and place it face down onto the output pile.
Let’s show it.




/**//// <summary>


/// 合并.得到:数组从区间[firstIndex,lastIndex]按照大小排列


/// </summary>


/// <param name="arr">已知数组,元素从区间[firstIndex,middleIndex]


/// 和[middleIndex+1,lastIndex]按照数值大小排列</param>


/// <param name="firstIndex">索引</param>


/// <param name="middleIndex">索引</param>


/// <param name="lastIndex">索引</param>


public static void Merge(Int32[] arr, Int32 firstIndex, Int32 middleIndex, Int32 lastIndex)




...{


Int32 n1 = middleIndex - firstIndex + 1;//left half,contain arr[middle]


Int32 n2 = lastIndex - middleIndex;//right


Int32[] left = new Int32[n1];


Int32[] right = new Int32[n2];


for (Int32 i = 0; i < n1; i++)


left[i] = arr[firstIndex + i];


for (Int32 j = 0; j < n2; j++)


right[j] = arr[middleIndex + 1 + j];


Int32 ii = 0;


Int32 jj = 0;


for (Int32 k = firstIndex; k <= lastIndex; k++)




...{


if (ii < n1 && jj < n2)




...{


if (left[ii] <= right[jj])


arr[k] = left[ii++];


else


arr[k] = right[jj++];


}


else if(ii==n1 && jj<n2)




...{


arr[k] = right[jj++];//left is empty


}


else if (jj == n2 && ii < n1)




...{


arr[k] = left[ii++];//right is empty


}


}


}



So,we get the merge function.Now sort the array is easy.We use the Merge peocedure as a subroutine in the merge sort algrithm.


public static void MergeSort(Int32[] arr, Int32 p, Int32 r)




...{


if (p < r)




...{


Int32 q = (p + r) / 2;


MergeSort(arr, p, q);


MergeSort(arr, q + 1, r);


Merge(arr, p, q, r);


}


}


If p>=r,the subarray has at most one element and is therefore already sorted.



The Merge sort’s running time is big theta n*lgn.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: