合并排序法(Merge Sort)
基于分治思想的合并排序,算法导论中的思考题,不加哨兵牌(sentinel card)的实现方式,实现很简单 : )
using System;
class MergeSort
{
public void merge(int[] A, int p, int q, int r)
{
int n1 = q-p+1;
int n2 = r-q;
int[] L = new int[n1];
int[] R = new int[n2];
for (int t=0; t<n1; t++) L[t] = A[p+t];
for (int t=0; t<n2; t++) R[t] = A[q+t+1];
int i = 0;
int j = 0;
int k = p;
while (i<n1 && j<n2) //一个数组输出完毕后跳出此循环
if (L[i] <= R[j])
A[k++] = L[i++];
else A[k++] = R[j++]; //L或R数组输出完毕后把另一个数组余下的部分全部输出
while (i<n1) A[k++] = L[i++]; //一下两个while永远只有一个执行,即未输出完的数组继续输出剩余部分
while (j<n2) A[k++] = R[j++];
}
public void sort(int[] A, int p, int r)
{
if (p<r)
{
int q = (p+r)/2;
sort(A, p, q);
sort(A, q+1, r);
merge(A, p, q, r);
}
}
}
class Program
{
public static void Main()
{
Random rnd = new Random();
int[] data = new int[10];
for (int i=0; i<10; i++)
{
data[i] = rnd.Next(100);
Console.Write("{0}\t",data[i]);
}
Console.WriteLine();
MergeSort s = new MergeSort();
s.sort(data, 0, 9);
for (int i=0; i<10; i++)
Console.Write("{0}\t",data[i]);
}
}
class MergeSort
{
public void merge(int[] A, int p, int q, int r)
{
int n1 = q-p+1;
int n2 = r-q;
int[] L = new int[n1];
int[] R = new int[n2];
for (int t=0; t<n1; t++) L[t] = A[p+t];
for (int t=0; t<n2; t++) R[t] = A[q+t+1];
int i = 0;
int j = 0;
int k = p;
while (i<n1 && j<n2) //一个数组输出完毕后跳出此循环
if (L[i] <= R[j])
A[k++] = L[i++];
else A[k++] = R[j++]; //L或R数组输出完毕后把另一个数组余下的部分全部输出
while (i<n1) A[k++] = L[i++]; //一下两个while永远只有一个执行,即未输出完的数组继续输出剩余部分
while (j<n2) A[k++] = R[j++];
}
public void sort(int[] A, int p, int r)
{
if (p<r)
{
int q = (p+r)/2;
sort(A, p, q);
sort(A, q+1, r);
merge(A, p, q, r);
}
}
}
class Program
{
public static void Main()
{
Random rnd = new Random();
int[] data = new int[10];
for (int i=0; i<10; i++)
{
data[i] = rnd.Next(100);
Console.Write("{0}\t",data[i]);
}
Console.WriteLine();
MergeSort s = new MergeSort();
s.sort(data, 0, 9);
for (int i=0; i<10; i++)
Console.Write("{0}\t",data[i]);
}
}