感觉自己这几篇都是主要参考的Wikipedia上的,快排就更加是了。。。。wiki上的快排挺清晰并且容易理解的,需要注意的地方我也添加上了注释,大家可以直接看代码。需要注意的是,wikipedia上快排的pivot选择的是末尾的数,而不是随机数

#include <iostream>
#include <vector>
using namespace std;

template<typename T>
void Quick_Sort( vector<T> &nums, int start, int end ){
	if( end <= start) return;
	T pivot = nums[end];//基准
	int left = start;
	int right = end-1;
	while( left < right ){
		while( nums[left] < pivot && left < right ) left++;
		while( nums[right] > pivot && left < right ) right--;
		swap( nums[right], nums[left] );
	}
	if( nums[left] >= nums[end] ){
		swap( nums[left],nums[end]); //处理pivot,如果大于等于,则在pivot的右侧,所以交换nums[end]和nums[left] ,此时以left为轴
		//左边小于nums[left]右边大于nums[left] 
	}
	else{
		left++; //如果nums[left] < pivot,则nums[left]属于pivot左侧,所以left++,不需要交换 
	}
	Quick_Sort( nums, start, left-1);   
	Quick_Sort( nums, left+1, end ); 
}

template <typename T>
void QuickSort( vector<T> &nums ){
	int start = 0;
	int end = nums.size(); 
	Quick_Sort(nums,start,end);
} 

int main(){
    vector<int> nums{25,7,37,47,13,13,30,15,4,1,12,49};
    cout<<" Before Sort:" ;
    for( auto m: nums){
        cout <<  m <<" ";
    }
    cout<<endl;
    QuickSort( nums );
    cout<< " After Sort:";
    for( auto m: nums){
        cout  << m <<" ";
    }
    cout<<endl;
} 

 

相关文章:

  • 2021-07-09
  • 2022-12-23
  • 2021-10-18
  • 2021-09-16
  • 2021-12-05
猜你喜欢
  • 2021-11-25
  • 2021-12-15
  • 2021-12-30
  • 2022-12-23
  • 2021-11-08
  • 2021-11-20
  • 2021-12-10
相关资源
相似解决方案