联系作者:humminwang@163.com
快速排序算法是一种基于交换的高效的排序算法,它采用了分治法的思想:
- 从数列中取出一个数作为基准数(枢轴,pivot)。
- 将数组进行划分(partition),将比基准数大的元素都移至枢轴右边,将小于等于基准数的元素都移至枢轴左边。
- 再对左右的子区间重复第二步的划分操作,直至每个子区间只有一个元素。
快速排序的时间复杂度在最坏情况下是 O ( N 2 ) O(N^2) O(N2),平均的时间复杂度是 O ( N ∗ l g N ) O(N*lgN) O(N∗lgN)。
STL C++
#include <algorithm>
using namespace std;
void sort(RanIt first, RanIt last, Pred pr);//前两个参数为迭代器指针,分别指向容器的首尾,第三个参数为比较方法。
比较方法有三种:
1、默认(不写):对于内置类型,按照升序排列;
2、标准库自带函数:functional提供了一堆基于模板的比较函数对象:equal_to<Type>、not_equal_to<Type>、greater<Type>、greater_equal<Type>、less<Type>、less_equal<Type>。升序:sort(begin,end,less<data-type>()); 降序:sort(begin,end,greater<data-type>()).
3、自定义函数:如
int cmp(const int &a,const int &b)
{
return a>b
}
快速排序详细实现 C++
int getIndex(int* nums,int low,int high)
{
int temp=nums[low];
while(low<high)
{
while(low<high&&nums[high]>=temp)
{
high--;
}
nums[low]=nums[high];
while(low<high&&nums[low]<=temp)
{
low++;
}
nums[high]=nums[low];
}
nums[low]=temp;
return low;
}
void quicksort(int* nums, int low, int high)
{
if(low<high)
{
int index =getIndex(nums,low,high);
quicksort(nums,low,index-1);
quicksort(nums,index+1,high);
}
}
Reference:
https://www.cnblogs.com/miracleswgm/p/9199124.html
https://www.cnblogs.com/AndyJee/p/4676146.html