zoukankan      html  css  js  c++  java
  • 两种快速排序 C++ 实现

    两种思路,第一种就是在数组两边放置两个指针,第二种是在数组左边放置两个快慢指针。第二种方法更简洁,并且可以扩展至单链表的情形。推荐使用

    #include <iostream>
    #include <vector>
    #include <string>
    #include <fstream>
    #include <sstream>
    #include <map>
    #include <ctime>
    #include <set>
    #include <algorithm>
    
    
    
    using namespace std;
    using namespace cv;
    
    int quick_sort(vector<int>& nums, int i_begin, int i_end){
        if(i_begin >= i_end){
            return 0;
        }
        int key = nums[i_begin];
        int left = i_begin;
        int right = i_end;
        while(left<right){
            while(left<right && nums[right] >= key){
                right--;
            }
            if(left < right){
                nums[left] = nums[right];
                left++;
            }
            while(left<right && nums[left] < key){
                left++;
            }
            if(left < right){
                nums[right] = nums[left];
                right--;
            }
        }
        nums[left] = key;
        quick_sort(nums, i_begin, left-1);
        quick_sort(nums, left+1, i_end);
        return 0;
    }
    
    
    
    int quick_sort_simple(vector<int>& nums, int begin, int end, int temp){
        if(begin>=end){
            return 0;
        }
        int key = nums[begin];
        int left = begin;
        int right = begin + 1;
        while(right != end){
            if(nums[right] < key){
                left++;
                temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
            }
            right++;
        }
        temp = nums[begin];
        nums[begin] = nums[left];
        nums[left] = temp;
    
        quick_sort_simple(nums, begin, left, 0);
        quick_sort_simple(nums, left + 1, end, 0);
        return 0;
    }
    
    
    
    int main(int argc, char* argv[])
    {
        vector<int> nums = {10, 5, 4, -10, 2, 0};
        for(auto i:nums){
            cout << i << ' ';
        }
    
        cout << endl;
    //    quick_sort(nums, 0, (int)nums.size() - 1);
        quick_sort_simple(nums, 0, (int)nums.size(), 0);
    
        for(auto i:nums){
            cout << i << ' ';
        }
        return 0;
    }
    
    
    
    
  • 相关阅读:
    Using Resource File on DotNet
    C++/CLI VS CSharp
    JIT VS NGen
    [Tip: disable vc intellisense]VS2008 VC Intelisense issue
    UVa 10891 Game of Sum(经典博弈区间DP)
    UVa 10723 Cyborg Genes(LCS变种)
    UVa 607 Scheduling Lectures(简单DP)
    UVa 10401 Injured Queen Problem(简单DP)
    UVa 10313 Pay the Price(类似数字分解DP)
    UVa 10635 Prince and Princess(LCS N*logN)
  • 原文地址:https://www.cnblogs.com/theodoric008/p/9383637.html
Copyright © 2011-2022 走看看