快排C++模板

#include <iostream>
#include <vector>
#include <stack>
#include <memory.h>
#include <unordered_map>
#include <queue>
#include <functional>

template<class T>
using compare = int(*)(const T&a, const T&b);

template<class T>
int my_compare(const T&a, const T&b) {
    return a <= b? -1: 1;
}

template<class T>
int my_partition(std::vector<T>& a, int low, int high, compare<T> f) {
    T flag = a[low];
    while (low < high) {
        while (low < high && f(flag, a[high]) <= 0) high--;
        a[low] = a[high];
        while (low < high && f(flag, a[low]) >= 0) low++;
        a[high] = a[low];
    }
    std::cout << flag << " " << a[low] << std::endl;
    a[low] = flag;
    return low;
}

template<class T>
void my_sort(std::vector<T>& a, int low, int high, compare<T> f) {
    if (low >= high) {
        return;
    }
    int mid = my_partition(a, low, high, f);
    my_sort(a, low, mid-1, f);
    my_sort(a, mid+1, high, f);
}

template<class T>
void my_sort(std::vector<T>& a, compare<T> f) {
    my_sort(a, 0, a.size()-1, f);
}


int  main() {
    std::vector<int> a = {31,12,12,34,1};
    my_sort(a, my_compare);
    for (int i = 0; i < 5; i++) {
        std::cout << a[i] << ",";
    }
    std::cout << std::endl;
//    int a[] = {1,2,3};
//    perm(a, 0, 3);
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 1 评论
分享
牛客网
牛客企业服务