Quick sort and three-way quick sort (c++ version)

Quick sort is an in-situ, unstable sorting algorithm, the worst-case running time is O(n^2), if randomization is used to select the pivot or the actual situation can achieve quick sorting when dividing sub-problems, it can make two sub-problems The problem size partitioning is constant proportional to keep the running time at O(n * lgn), and a good or bad partitioning only changes its constant factor.
The three-way quick sort is mainly to solve the problem that when there are a large number of identical elements in the sequence, it still needs O(n * lgn) on average through quick sort, while the three-way quick sort only needs O(n) when all elements are the same

Its implementation is given below;

#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;
//快速排序(选取序列首元素为主元)
int partition_1(vector<int>& vec,const int& lo,const int& hi) {
    int i = lo;
    int j = hi + 1;
    while (true) {
        while (vec[lo] > vec[++i]) if (i == hi) break;
        while (vec[lo] < vec[--j]) if (j == lo) break;
        if (i >= j) break;
        std::swap(vec[i], vec[j]);
    }
    std::swap(vec[j], vec[lo]);
    return i;
}
//快速排序(选取序列尾元素为主元)
int partition_2(vector<int>& vec, const int& lo, const int& hi) {
    int i = lo - 1;
    int j = hi;
    while (true) {
        while (vec[hi] > vec[++i]) if (i == hi) break;
        while (vec[hi] < vec[--j]) if (j == lo) break;
        if (i >= j) break;
        std::swap(vec[i], vec[j]);
    }
    std::swap(vec[i], vec[hi]);
    return i;
}
void Quick_Sort(vector<int>& vec,const int& lo,const int& hi) {
    if (lo >= hi) {
        return;
    }
    int j = partition_2(vec, lo,hi);
    Quick_Sort(vec, lo, j - 1);
    Quick_Sort(vec, j + 1, hi);
}
void Quick_Sort(vector<int>& vec) {
    Quick_Sort(vec, 0, vec.size() - 1);
}
//三向快速排序
void Three_Quick_Sort(vector<int>& vec,const int& lo,const int& hi) {
    if (lo >= hi) {
        return;
    }
    int elpos = lo;
    int erpos = hi;
    int i = lo + 1;
    int temp = vec[lo];
    while (elpos < erpos && i <= hi) {
        if (vec[i] < temp) {
            swap(vec[i++], vec[elpos++]);
        }else if (vec[i] > temp) {
            swap(vec[i], vec[erpos--]);
        }else {
            ++i;
        }
    }
    Three_Quick_Sort(vec, lo, elpos - 1);
    Three_Quick_Sort(vec, erpos + 1, hi);
}
void Three_Quick_Sort(vector<int>& vec) {
    Three_Quick_Sort(vec, 0, vec.size() - 1);
}
int main(int argc,char** argv) {
    //vector<int> vec{ 9,8,1,6,5,4,9 };
    //vector<int> vec{ 9,8,7,6,5,4,3,2,1,0 };
    vector<int> vec{ 1,6,2,0,8,5,4,3,7,9 };
    //Quick_Sort(vec);
    Three_Quick_Sort(vec);
    for (auto& v : vec) {
        cout << v << endl;
    }
    system("pause");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324840510&siteId=291194637