zoukankan      html  css  js  c++  java
  • 排序算法总结(四)快速排序【QUICK SORT】

    感觉自己这几篇都是主要参考的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;
    } 
    

     

  • 相关阅读:
    DOM
    笔试题
    小案例
    前端基础面试题
    2048小游戏
    JS原型与构造函数
    String字符串和正则表达式
    数组
    MySQL_PHP学习笔记_2015_0906_使用PHP模板
    MySQL_PHP学习笔记_2015_0614_PHP传参总结_URL传参_表单传参
  • 原文地址:https://www.cnblogs.com/rockwall/p/5742691.html
Copyright © 2011-2022 走看看