归并排序

来源:互联网 发布:吉他软件电脑版 编辑:程序博客网 时间:2024/06/06 08:44

归并类

// MergeSort.h#include <iostream>template <typename T> class MergeSort{public:    static void mergeSort(T *nums, int left, int right){        if (left >= right)            return;        int pos = (left + right) >> 1;        mergeSort(nums, left, pos);        mergeSort(nums, pos + 1, right);        merge(nums, left, pos, right);    }private:    static void merge(T *nums, int left, int pos, int right){        int low = left;        int high = pos+1;        T *temp = new T[right - left + 1];        int idx = 0;        while (low <= pos && high <= right){            if (nums[low] > nums[high]){                temp[idx++] = nums[high];                ++high;            }            else{                temp[idx++] = nums[low];                ++low;                      }        }        while (low <= pos){ temp[idx++] = nums[low++]; }        while (high <= right){ temp[idx++] = nums[high++]; }        for (int i = 0; i < idx; ++i){            nums[left + i] = temp[i];        }        delete[] temp;    }};

main func

#include <iostream>#include "MergeSort.h"using namespace std;int main(){    int data[] = { 12, 34, 54, 2, 576, 45, 8, 59 };    int len = sizeof(data) / sizeof(data[0]);    MergeSort<int>::mergeSort(data, 0, len - 1);    for (auto d : data){        std::cout << d << " ";    }    system("pause");    return 0;}
原创粉丝点击