基础算法题复习之一:快速排序

先对排序算法来个总结: 

 其中不稳定的有:快,选,希,堆

时间复杂度为O(NlogN)的有:快,归,堆,   其中后两者的平均最好和最坏的时间复杂度都一样,而快速排序的最差复杂度为O(n^2),即初始排序为完全逆序的时候,所以快速排序的性能是会受到初始排序的影响的;

即稳定时间复杂度又低的最优排序算法应该是归并排序,但是归并算法的空间复杂度为O(N)

希尔排序的平均,最好,最坏的时间复杂度都不一样

除了归并排序和快速排序,其他排序算法的空间复杂度都是O(1)

快速排序是不稳定的排序,算法复杂度为o(nlogn);

#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//快速排序
int partition(vector<int> & nums, int low, int high)
{
	int r = (nums[low] + nums[high] + nums[(low + high) / 2]) / 3;//这里的关键字采用三平均分区法,
	//也可以使用第一个或者随机法,如:
	//r=(nums[low]);
	//r=low+rand()%(high-low+1);
	while (low < high)
	{
		if (nums[low] < r)
			low++;
		if (nums[high] > r)
			high--;
		swap(nums[low], nums[high]);
	}
	swap(nums[low],r);//在low位置前的都小于r,在low位置后面的都大于r;
	return low;
}
void   quicksort(vector<int> & nums,int low,int high)
{	
	int index = partition(nums,low,high);
	if(index>low)
	quicksort(nums,low,index-1);
	if(index<high)
	quicksort(nums, index+1, high);
}
int main()
{
	vector<int>  nums{1,4,2,3,5,9,8,6,7,0,10,14,23,20,19,68};
	quicksort(nums,0,nums.size()-1);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cxy19931018/article/details/81839298