【快速排序】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); } } */
相关文章推荐
- js实现常见的三种排序方法(冒泡排序、快速排序、归并排序)
- 快速排序的三种实现方法体会
- 快速排序三种实现方法
- C++ 快速排序QuickSort的实现
- C++实现几种常用的时间复杂度为O(nlogn)的排序方法:归并排序、快速排序、堆排序、希尔排序
- 学习笔记:快速排序的C++、JavaScript(2种方法)、Java实现
- 算法导论 - QuickSort 快速排序 C++实现
- c++实现数据结构中的各种排序方法:直接插入、选择,归并、冒泡、快速、堆排序、shell排序
- C++实现模板顺序表和三种排序方法
- 快速排序模板方法,只实现了int比较的仿函数
- 快速排序 c++ 实现
- 堆排序,快速选择排序,快速选择排序,归并排序的c++实现
- c++中的三种排序,比较基础,因为作为一个编程员总要会几种排序方法
- [C++] 用VC 6.0实现串行通信的三种方法
- 快速排序的不同语言不同方法实现的…
- [算法入门]快速排序非递归方法(Java实现),大家一起来找茬啊~
- c++实现冒泡,选择,插入,快速排序
- C++实现快速排序
- PHP基于ICU扩展intl快速实现汉字转拼音及按拼音首字母分组排序的方法
- 选择排序、冒泡排序、插入排序、基数排序、快速排序、归并排序完整C++实现