static void Merging_Sort_Beta(int[] a) //归并排序算法(非递归)
{
int gap = 1;
int len = a.Length ;
int[] Temp=new int[a.Length];
while (gap < a.Length)
{
MergePass(a, Temp, gap, len);
gap = gap * 2;
MergePass(Temp, a, gap, len);
gap = gap * 2;
}
}
static void MergePass(int[] Source, int[] Temp, int gap, int len)
{
int i = 0;
while (i < len – 2 * gap + 1)
{
Merge_Beta(Source, Temp, i, i + gap – 1, i + 2 * gap – 1);
i =i + 2 * gap;
}
if (i < (len – gap))
{
Merge_Beta(Source, Temp, i, i + gap – 1, len-1);
}
else
{
for (int j = i; j < len; j++)
Temp[j] = Source[j];
}
}
static void Merge_Beta(int[] Source, int[] Temp, int start, int middle, int end) //合并Source数组,合并时排序,排序后的结果输出到Temp数组
{
int i = start;
int j = middle + 1;
int k = start;
while (i <= middle && j <= end)
{
if (Source[i] <= Source[j]) //取左半边和右半边比较,取较小值写入数组
Temp[k++] = Source[i++];
else
Temp[k++] = Source[j++];
}
while (i <= middle) //将左半边剩余元素写入数组
Temp[k++] = Source[i++];
while (j <= end) //将右半边剩余元素写入数组
Temp[k++] = Source[j++];
}