zoukankan      html  css  js  c++  java
  • C++ Primer中的一个sort算法源码

    该算法采用分而治之的方法来进行排序,思想不错

     1 //排序里面有std的sort了,效率更高,这个例子不是为了取代std::sort的,放在这里是做为一个例子体现分而治之的思想
     2 template<typename Type>
     3 Type min(Type a, Type b) {
     4     //Type 类型需要实现了小于号的重载
     5     return a < b ? a : b;
     6 }
     7 
     8 template<typename elemType>
     9 void swap(std::vector<elemType> &array, int i, int j) {
    10     elemType tmp = array[i];
    11     array[i] = array[j];
    12     array[j] = tmp;
    13 }
    14 
    15 template<typename elemType>
    16 void sort(vector<elemType> &array, int low, int high) {
    17     if(low < high) {
    18         int lo = low;
    19         int hi = high + 1;
    20         elemType elem = array[lo];
    21 
    22         while(1) {
    23             while(min(array[++lo], elem) != elem && lo < high);
    24             //find the value bigger than low elem
    25             while(min(array[--hi], elem) == elem && hi > low);
    26             //find the value smaller than low elem
    27             if(lo < hi) // if bigger value is before the smaller value,swap them
    28                 swap(array, lo, hi);
    29             else break;
    30         }
    31         swap(array, low, hi);//the hi value smaller than low elem ,swap them
    32         sort(array, low, hi-1);
    33         sort(array, hi+1, high);
    34     }
    35 }
  • 相关阅读:
    9.17
    9.14
    9.13
    9.13
    9.11
    9.28
    10 .19 知识点
    redux
    react路由
    react的三大属性
  • 原文地址:https://www.cnblogs.com/jojodru/p/2494652.html
Copyright © 2011-2022 走看看