C++归并排序模版
老规矩,先来头文件StoreUtil.h
#include <iostream> #ifndef SORTUTIL_H #define SORTUTIL_H class SortUtil { public: template <class T> void MergeSort(T randomArray[], int left, int right); //归并推排序,left和right为下标 template <class T> void Merge(T A[], int left, int mid, int right); //合并数组 }; #endif
再来SortUtil.cpp
#include <iostream> #include "SortUtil.h" using namespace std; template <class T> void SortUtil::MergeSort(T randomArray[], int left, int right) { int mid; if (left < right) { mid = (left+right)/2; MergeSort(randomArray, left, mid); //分割左边的序列 MergeSort(randomArray, mid+1, right); //分割右边的序列 Merge(randomArray, left, mid+1, right+1); //归并序列 } } template <class T> void SortUtil::Merge(T A[],int left, int mid, int right) { T* temp = new T[left+right]; int i = left, j = mid, k = 0; while (i < mid && j < right) { if (A[i] <= A[j]) temp[k++] = A[i++]; else temp[k++] = A[j++]; } while (i < mid) temp[k++] = A[i++]; while (j < right) temp[k++] = A[j++]; for (i = left, k = 0; i < right; i++, k++) A[i] = temp[k]; }
最后是main.cpp
#include <iostream> #include "SortUtil.cpp" #include <ctime> using namespace std; int main() { srand((unsigned)time(0)); SortUtil sortUtil; int test[1000]; int length = 1000; for (int i = 0; i < length; i++) { test[i] = length - i; } sortUtil.MergeSort(test, 0, length-1); for (int i = 0; i < length; i++) { cout<<test[i]<<" "; } cout<<endl; }