快速排序原理
快速排序是一种分治的排序算法,使用切分元素将一个数组分成两个子数组,将两部分独立地排序,当两个子数组都有序时整个数组也就自然有序了.
C/C++实现
int partition(int a[], int low, int high)
{
int i = low, j = high + 1; //左右扫描指针
int v = a[low];//切分元素
int temp;
while (true) //扫描左右,检查扫描是否结束并交换元素
{
while (a[++i] < v)
if (i == high)
break;
while (v < a[--j]);
if (i >= j)
break;
swap(a[i],a[j]);
}
swap(a[low], a[j]);
return j;
}
void QuickSort(int a[], int low, int high)
{
if (high <= low)
return;
int index = partition(a, low, high);
QuickSort(a, low, index - 1);
QuickSort(a, index + 1, high);
}
void QuickSort(int a[], int size)
{
random_shuffle(a, a + size);
QuickSort(a, 0, size - 1);
}
C#实现
public static void QuickSort(int[]a)
{
QuickSort(a, 0, a.Length - 1);
}
private static void QuickSort(int[]a,int low, int high)
{
if (high <= low)
return;
int index = partition(a, low, high);
QuickSort(a, low, index - 1);
QuickSort(a, index + 1, high);
}
private static int partition(int[]a, int low, int high)
{
int l = low, r = high + 1;
int v = a[low];
int temp;
while (true)
{
while(a[++l] < v)
{
if (l == high)
break;
}
while (v < a[--r]) ;
if (l >= r)
break;
temp = a[l];
a[l] = a[r];
a[r] = temp;
}
temp = a[r];
a[r] = a[low];
a[low] = temp;
return r;
}
由于C#没有自带的shuffle函数,我嫌麻烦没有找,如果想要更稳定,可以在网上找找.
总结:快速排序最多需要N的平方/2次比较,如果随机打乱数组可以预防这种情况,它是一个偏爱随机性的算法.