递归和非递归版本的快速排序


#include <iostream>
#include <vector>
#include <stack>


template <typename T> 
void swap(T * t1, T * t2) {
    T tmp = *t1;
    *t1 = *t2;
    *t2 = tmp;
}

// 递归版本
void quicksort(std::vector<int> & vec, int begin, int end) {
    if (begin >= end) {
        return;
    }
    if (end - begin == 1) {
        if (vec[begin] > vec[end])
            swap(&vec[begin], &vec[end]);
    }

    int povit = vec[begin];
    int i = begin;
    int j = end;
    while(true) {
        while(j > i && vec[j] >= povit) j--;
        if (j == i) {
            break;
        }
        vec[i] = vec[j];

        while(j > i && vec[i] <= povit) i++;
        if (j == i) {
            break;
        }
        vec[j] = vec[i];
    }

    vec[i] = povit;

    quicksort(vec, begin, i-1);
    quicksort(vec, i+1, end);
}

int partition(std::vector<int> & vec, int begin, int end) {
    if (begin >= end) {
        return -1;
    }
    if (end - begin == 1) {
        if (vec[begin] > vec[end])
            swap(&vec[begin], &vec[end]);
        return -1;
    }
    int povit = vec[begin];
    int i = begin;
    int j = end;
    while(true) {
        while(j > i && vec[j] >= povit) j--;
        if (j == i) {
            break;
        }
        vec[i] = vec[j];

        while(j > i && vec[i] <= povit) i++;
        if (j == i) {
            break;
        }
        vec[j] = vec[i];
    }
    vec[i] = povit;
    return i;
}

// 非递归版本
void quicksort_no_recur(std::vector<int> & vec) {
    if (vec.size() < 2) {
        return;
    }
    std::stack<std::pair<int, int> > st;
    st.push({0, vec.size()-1});
    while(st.size() != 0) {
        auto lastIndex = st.top();
        st.pop();
        auto i = partition(vec, lastIndex.first, lastIndex.second);
        std::cout << "partition i = " << i << ", first = " << lastIndex.first << ", " << lastIndex.second << std::endl;
        if (i < 0) {
            continue;
        }
        st.push({lastIndex.first, i-1});
        st.push({i+1, lastIndex.second});
    }
}

int main() {

    std::vector<int> vec = {10, 1, 8, 6, 5, 7, 4};
   // quicksort(vec, 0, vec.size() -1);
    quicksort_no_recur(vec);
    for (auto & item : vec) {
        std::cout << item << ",";
    }
    std::cout << std::endl;
    return 0;
}

上一篇:矢量分析与场论(节选)


下一篇:算法题目——多米诺骨牌问题(POJ-2663)