两种快速排序 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;
}



原文地址:https://www.cnblogs.com/theodoric008/p/9383637.html