【IT168 技术文档】快速排序是经典的排序方法。
实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortPractice
{
class MyQuickSorter
{
public int[] Sort(int[] src,int leftIndex,int rightIndex)
{
int left = leftIndex;
int right =rightIndex;
if (left < right)
{
int i = left;
int j = right + 1;
int guard = src[left];
int temp = 0;
do
{
do
{
i++;
}
while ( i < right &&src[i] < guard);
do
{
j--;
}
while (src[j] > guard && j > left);
if (i < j)
{
temp = src[i];
src[i] = src[j];
src[j] = temp;
}
} while (i < j);
temp = src[j];
src[j] = guard;
//guard = temp;
src[left] = temp;
Sort(src, left, j - 1);
Sort(src, j+1, rightIndex);
}
return null;
}
}
}
单元测试:
///
///Sort 的测试
///
[TestMethod()]
[DeploymentItem("SortPractice.exe")]
public void SortTest()
{
MyQuickSorter_Accessor target = new MyQuickSorter_Accessor(); // TODO: 初始化为适当的值
int TestCount=10000;
int ArraySize=300;
Random r = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < TestCount; i++)
{
List arr = new List();
for (int j = 0; j < ArraySize; j++)
{
arr.Add(r.Next());
}
int[] src = arr.ToArray();
int[] after =(int[]) src.Clone();
target.Sort(after, 0, after.Length - 1);
Array.Sort(src);
bool equal=IntEqualInArray(src,after);
Assert.IsTrue(equal);
}
}
bool IntEqualInArray(int[] src, int[] after)
{
if (src.Length != after.Length)
{
return false;
}
for (int i = 0; i < src.Length; i++)
{
if (src[i] != after[i])
{
return false;
}
}
return true;
}