快速排序的平均时间最好,O(nlgn),最差的时候为每次选择的枢轴为第一个,相当于冒泡排序O(n^2)。空间复杂度 O(lgn);//利用的递归栈
自己的思路是:先选第一个为枢轴,然后从下一个元素开始进行划分,右边是大于的,左边是小于的。先进行比较,俩边进行,交换俩端不符合的,也即交换右边为大的,左端小的,之后继续,最后的时候要么刚好A[low] < pivot,则直接为枢轴位置,交换下即可,要么因为low 要回退一个,即low指向的下一个位置。
个人写的程序确实没有,书上的精简。
第二个函数思路:用俩端的数据填充因挖掉枢轴产生的空缺,并且最终刚好low == high时即为枢轴,刚好留下空缺直接填充即可。代码很精简!!
具体解释大家可以参考:http://blog.csdn.net/morewindows/article/details/6684558
#include <iostream>
#include <cassert>
#include <algorithm>
using namespace std;
int partition(int *A,int low,int high);
void qsort(int *A,int n);
int q_partition(int *A,int low,int high);
void q_sort(int *A,int n);
int main()
{
int A[10] = {2,3,5,1,7,8,4,0,9,6};//{2,3,5,1,7,8,4,0,9,6};
qsort(A,8);
for (int i = 0;i < 8;i++)
{
cout<<A[i]<<endl;
}
cout<<"----------"<<endl;
int B[10] = {2,3,5,1,7,8,4,0,9,6};
q_sort(B,10);
for (int i = 0;i < 10;i++)
{
cout<<B[i]<<endl;
}
return 0;
}
void qsort(int *A,int n)
{
if (n <= 1)
{
return;
}
int index = partition(A,0,n-1);
//cout<<"index:"<<index<<endl;
qsort(A,index);
qsort(A+index+1,n - index-1);
}
int partition(int *A,int low,int high)
{
// 选第一个为枢轴,或者取第一个,最后一个,中间的一个元素的中间值
assert(A&& low <= high && low >=0);
if (low == high)
{
return low;
}
int pivot = A[low];
int pivot_index = low;
low = low + 1;
while(low < high)
{
while(low < high && A[high] > pivot) high-- ;
while(low < high && A[low] < pivot) low++;
if (low < high)
{
swap(A[low],A[high]);
low ++;
high--;
}
}
if (A[low] < pivot)
{
swap(A[low],A[pivot_index]);
}
else
{
low--;
swap(A[low],A[pivot_index]);
}
return low;
}
void q_sort(int *A,int n)
{
if (n <= 1)
{
return;
}
int index = q_partition(A,0,n-1);
//cout<<"index:"<<index<<endl;
q_sort(A,index);
q_sort(A+index+1,n - index-1);
}
int q_partition(int *A,int low,int high)
{
assert(A&& low <= high && low >=0);
//挖空
int pivot = A[low];
while(low < high)
{
while(low < high && A[high] > pivot) high -- ;
A[low] = A[high];// 填空缺
while(low < high && A[low] < pivot) low ++;
A[high] = A[low];
}
A[low] = pivot;
return low;
}