快速排序(Quick Sort) 详解 及 代码(C++)
本文地址: http://blog.csdn.net/caroline_wendy/article/details/24485687
快速排序(Quick Sort): 通过一趟排序将带排记录分割成独立的两部分, 其中一部分值较小, 一部分值较大,
再分别对两部分进行排序, 最终达到有序.
通过两个指针low和high, 分别指向首尾, 把枢轴(pivot)和首尾部分, 不同的值交换, 较大部分交换小的值, 较小部分交换大的值,
最后保证, 枢轴是较大值和较小值的分界点, 再使用递归把所有部分排列.
快速排序目前被认为是最好的一种排序方法, 时间复杂度(nlogn), 而且是同等排序中,平均性能最好的方法.
但是使用递归算法, 需要栈空间保存数据.
代码:
/*
* test.cpp
*
* Created on: 2014.4.23
* Author: Spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
void print(const std::vector<int>& L) {
for (auto i : L) {
std::cout << i << " ";
}
std::cout << std::endl;
}
int Partition(std::vector<int>& L, int low, int high) {
int pivotkey = L[low];
while (low < high) {
while (low<high && L[high]>=pivotkey)
--high;
L[low] = L[high];
while (low<high && L[low]<=pivotkey)
++low;
L[high] = L[low];
}
L[low] = pivotkey;
print(L);
return low;
}
void QSort(std::vector<int>& L, int low, int high) {
if (low < high) {
int pivotloc = Partition(L, low, high);
QSort(L, low, pivotloc-1);
QSort(L, pivotloc+1, high);
}
}
void QuickSort(std::vector<int>& L){
QSort(L, 0, L.size());
}
int main(void) {
std::vector<int> L = {49, 38, 65, 97, 76, 13, 27, 49, 55, 4};
print(L);
QuickSort(L);
print(L);
std::cout << "result : "; print(L);
}
输出:
49 38 65 97 76 13 27 49 55 4
4 38 27 13 49 76 97 49 55 65
4 38 27 13 49 76 97 49 55 65
4 13 27 38 49 76 97 49 55 65
4 13 27 38 49 76 97 49 55 65
4 13 27 38 49 65 55 49 76 97
4 13 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97
result : 4 13 27 38 49 49 55 65 76 97