今天中午有空,幫人寫了個關於合並排序的算法(递归C#版)
先看下合並排序的基本策略思想——平衡、简单二分分治:
• 将待排序元素叙列简单地分成大小大致相等的左
• 右两段,接着依次分别对这两段子叙列递归地进
• 行合并排序,然后利用这两段子叙列已得到的有
• 序性,将它们有序地合并在一个工作区,最后用
• 工作区中排好序的全叙列更新原待排序的元素叙
• 列成为所要求的排好序的元素叙列。
調用形式如下:
int[] ar = {1,4,34,8,78,4,5,6,9,34,65,78,9,12};
this.MergeSoft(ref ar,0,ar.Length-1);
for(int i=0;i<ar.Length;i++)
{
ar[i];
}
this.MergeSoft(ref ar,0,ar.Length-1);
for(int i=0;i<ar.Length;i++)
{
ar[i];
}
遞歸程式如下
private void MergeSoft(ref int[] arrA,int left,int right)
{
if(left<right)
{
int mid = (left+right)/2;
MergeSoft(ref arrA,left,mid);
MergeSoft(ref arrA,mid+1,right);
int[] arrC = Merge(arrA,left,mid,right);
CopyArray(ref arrA,arrC,left,right);
}
}
{
if(left<right)
{
int mid = (left+right)/2;
MergeSoft(ref arrA,left,mid);
MergeSoft(ref arrA,mid+1,right);
int[] arrC = Merge(arrA,left,mid,right);
CopyArray(ref arrA,arrC,left,right);
}
}
private int[] Merge(int[] arrA,int left,int mid,int right)
{
int[] arrB = new int[right-left+1];
int i= left, j=mid+1, k=0;
while((i<=mid) && j<=right)
if(arrA[i]<=arrA[j]) arrB[k++] = arrA[i++];
else arrB[k++] = arrA[j++];
if(i>mid && j<=right)
for(int q=j; q<=right;q++)
arrB[k++] = arrA[q];
if(j>right && i<=mid)
for(int q=i; q<=mid;q++)
arrB[k++] = arrA[q];
return arrB;
}
{
int[] arrB = new int[right-left+1];
int i= left, j=mid+1, k=0;
while((i<=mid) && j<=right)
if(arrA[i]<=arrA[j]) arrB[k++] = arrA[i++];
else arrB[k++] = arrA[j++];
if(i>mid && j<=right)
for(int q=j; q<=right;q++)
arrB[k++] = arrA[q];
if(j>right && i<=mid)
for(int q=i; q<=mid;q++)
arrB[k++] = arrA[q];
return arrB;
}
private void CopyArray(ref int[] arrA,int[] arrC,int left,int right)
{
for(int i=left,j=0;i<=right && j<arrC.Length;i++,j++)
arrA[i] = arrC[j];
}
{
for(int i=left,j=0;i<=right && j<arrC.Length;i++,j++)
arrA[i] = arrC[j];
}