C++源代码:
#include<iostream>
using namespace std;
int partition(int * a, int low, int high){
//指定数组a中的一个元素pos,使pos这个元素
//在正确的位置上,即pos左边的元素都小于等于pos,右边的元素都大于等于pos
int pos = a[low];
while (low<high){
while (low < high&&a[high] > pos)
high--;
a[low] = a[high];
while (low < high&&a[low] < pos)
low++;
a[high] = a[low];
}
a[low] = pos;
return low;
}
void QuickSort(int * a, int low, int high){
if (low < high){
int p = pasition(a, low, high);
QuickSort(a, low, p - 1);
QuickSort(a, p + 1, high);
}
}
int main(){
int a[] = { 8, 5, 2, 3, 6, 7, 4, 9 };
QuickSort(a, 0, 7);
for (int i = 0; i <= 7; i++)
cout << a[i] << endl;
}
非递归:
#include<iostream>
#include<Queue>
class LH
{
public:
LH(int l, int h){
low = l;
high = h;
}
int low;
int high;
};
using namespace std;
int Partition(int * a, int low, int high){
int pos = a[low];
while (low<high){
while (low < high&&a[high] > pos)
high--;
a[low] = a[high];
while (low < high&&a[low] < pos)
low++;
a[high] = a[low];
}
a[low] = pos;
return low;
}
void QuickSort(int * a, int low, int high){
queue<LH> que;
que.push(LH(low, high));
while (!que.empty()){
LH lh = que.front();
que.pop();
int pos = Partition(a, lh.low, lh.high);
if (lh.low < pos - 1)
que.push(LH(lh.low, pos - 1));
if (lh.high > pos + 1)
que.push(LH(pos + 1, lh.high));
}
}
int main(){
int a[] = { 8, 5, 2, 3, 6, 7, 4, 9 };
QuickSort(a, 0, 7);
for (int i = 0; i <= 7; i++)
cout << a[i] << endl;
}
以上是可以运行的代码,当然,position函数还有另一种写法,两者作用是完全一样的
int pasition(int * a, int low, int high){
int pos = a[low];
while (low<high){
while (low < high&&a[high] > pos)
high--;
//a[low] = a[high];
int c = a[low]; a[low] = a[high]; a[high] = c;
while (low < high&&a[low] < pos)
low++;
//a[high] = a[low];
c = a[low]; a[low] = a[high]; a[high] = c;
}
//a[low] = pos;
return low;
}
。。。 | 最好情况 | 最坏情况 |
---|---|---|
时间复杂度 | O(nlog2n) | O(n2) |
空间复杂度 | O(log2n) | O(n) |
情况 | 每次划分都能从中间划分 | 元素有序或者逆序 |
快速排序时间复杂度推导
http://blog.youkuaiyun.com/weshjiness/article/details/8660583