您的位置:首页 > 编程语言 > C语言/C++

【快速排序】QuickSort(三种实现方法)c++描述

2011-09-14 19:39 597 查看
//以下算法详解,可以在《计算机算法设计与分析》(王晓东,三版)和《数据结构》(严蔚敏)中找到详解。

#include <iostream>
using namespace std;
/*
int Random(int low,int high);

template <class Type>
void RandomizedQuickSort(Type a[],int low,int high);

*/

/*
template <class Type>
void SWAP(Type a[],int i,int j);
*/

template <class Type>
void QuickSort(Type a[],int low,int high);

template <class Type>
int Partition(Type a[],int low,int high);

int main (int argc, const char * argv[])
{
int a[] = {-1,2,5,34,56,3,55,57}; //0位置不用,作为pivot暂存。
int high = 7;
int low = 1;
QuickSort(a, low, high);
for (int i = 1; i<8; i++) {
cout<<a[i]<<" ";
}
return 0;
}

//常规的解法 。。。。。。。。。。。。。。。。。
template <class Type>
void QuickSort(Type a[],int low,int high)
{
if (low < high) {
int pivot = Partition(a, low, high);
QuickSort(a,low,pivot-1);
QuickSort(a,pivot+1,high);
}
}

template <class Type>
int Partition(Type a[],int low,int high)
{
a[0] = a[low];//pivotKey
Type pKey = a[low];
while (low < high) {
while (a[high] >= pKey && low < high ) high--;
a[low] = a[high];
while (a[low] <= pKey && low < high) low++;
a[high] = a[low];
}
a[low] = a[0];
return low;
}

template <class Type>
void SWAP(Type a[],int i,int j)
{
Type temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}

// 另一种partition的算法...参考《计算机算法设计与分析》...............................
/*
template <class Type>
int Partition(Type a[],int low,int high)
{
int i = low - 1,j = high + 1;
Type x = a[low];
while (true) {  //i逐渐增大,j逐渐减小,之道a[i]>=x>=a[j]
while (a[++i] < x && i<j);
while (a[--j] > x);
if (i >= j)
break;
SWAP(a,i,j);  //如果i<j,交换。
}
a[low] = a[j];
a[j] = x;
return j;
}*/

//效率更高的随机化算法
/*
//因为pivot的选择对快排的影响非常大,所以采用随即化的算法,算法的稳定性更高。
//更容易达到我们期望的平均时间复杂度O(nlogn)
int Random(int low,int high)
{
return rand()%(high - low + 1) + low; //产生一个low~high之间的随机数.
}

template <class Type>
int RandomizedPartition(Type a[],int low,int high)
{
int pivot = Random(low,high);
SWAP(a,pivot,low); //a[pivot] 与 a[low] 交换
return Partition(a, low, high);
}

template <class Type>
void RandomizedQuickSort(Type a[],int low,int high)
{
if (low < high) {
int pivot = RandomizedPartition(a, low, high);
RandomizedQuickSort(a,low,pivot-1);
RandomizedQuickSort(a, pivot+1, high);
}
}
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息