手撕代码之快速排序算法(简单明了)
介绍
快速排序算法是一个很受欢迎的不稳定排序算法,在数据完全无须的情况下,最容易发挥其长处,此时的时间复杂度为nlognnlognnlogn,当数据在完全有序的情况下,此时的时间复杂度为n2n^2n2,另外快速排序的空间复杂度也很高哦,为O(log2n)O({log_2}n)O(log2n)∼\sim∼O(n)O(n)O(n)之间,是除了基数排序中,空间复杂度最高的算法,这是典型的空间换时间的算法。
好了,下面看下怎么去一步一步实现快速排序吧,在这里就不多说快速排序算法了(可以参考网上教程),只展示源代码啦~
源代码
下面源代码使用了左右指针的方式,并选择一个基数作为快速排序的参考标准,左右数据进行比较,并在原数组上进行操作。
#include<iostream>
#include <vector>using namespace std;void fastsort(vector<int>& point,int num)
{if (point.size() == 0 || point.size() == 1) return;int basenum = num;int left = 0, right = point.size() - 1;while (left != right){if (point[left] < basenum)left++;if (point[right] >= basenum)right--;if (point[left] >= basenum&&point[right] < basenum){int tmp = 0;tmp = point[left];point[left] = point[right];point[right] = tmp;}}}
int main()
{vector<int> point = { 3, 1, 2, 6, 5, 4,9, 7, 10, 8 };fastsort(point,6);for (int i = 0; i < point.size(); i++){cout << point[i] << endl;}system("pause");return 0;
}