快速排序(c++模板实现)

#ifndef SORT_H
#define SORT_H

#include <iostream>
#include <ctime>

namespace jdw {

template <typename Iterator, typename Comp>
Iterator partition(Iterator first, Iterator last, Comp comp)
{
    if (first >= last) {
        return last;
    }
    srand(time(0));
    int random = rand() % (last - first);
    std::swap(*first, *(first + random));
    auto pivot = *first;
    auto left = first;
    auto right = last - 1;
    while (left < right) {
        while (left < right && (comp(pivot, *right) || !comp(*right, pivot))) --right;
        while (left < right && (comp(*left, pivot) || !comp(pivot, *left))) ++left;
        std::swap(*left, *right);
    }
    std::swap(*left, *first);
    return left;
}

template <typename Iterator, typename Comp>
void quickSort_aux(Iterator first, Iterator last, Comp comp)
{
    auto iter = partition(first, last, comp);
    if (iter == last) return ;
    quickSort_aux(first, iter, comp);
    quickSort_aux(iter + 1, last, comp);
}

template <typename Iterator, typename Comp = std::less<typename Iterator::value_type>>
void sort(Iterator first, Iterator last, Comp comp = std::less<typename Iterator::value_type>())
{
    quickSort_aux(first, last, comp);
}

template<typename Container>
void print(const Container& container) {
    for (auto& e : container) {
        std::cout << e << " ";
    }
    std::cout << std::endl;
}

} 

#endif
#include "sort.h"

#include <vector>

template <typename T>
void test_jdw_quicksort(std::vector<T>& nums) {
    jdw::sort(nums.begin(), nums.end());
    jdw::print(nums);
    jdw::sort(nums.begin(), nums.end(), std::greater<T>());
    jdw::print(nums);
}

int main() {
    std::vector<int> nums1{5,9,-85,6,20,0,-6,33,44,23,99};
    test_jdw_quicksort(nums1);
    std::vector<int> nums2(20, 0);
    test_jdw_quicksort(nums2);
    std::vector<char> chars{'3', 'a', 'A', 'S', 'D', '0', '+', '*', '&'};
    test_jdw_quicksort(chars);
    std::vector<double> ds{1.2, -2.3, 4.5, 4.77, 5123, 3.1321, -22222, 31.323, 11.0};
    test_jdw_quicksort(ds);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值