算法导论(4)归并排序
#pragma once #include<limits> /*合并两个已经排序好的子序列 两个已经排序好的子序列为src[startIndex]-src[middleIndex];src[middleIndex+1]-src[endIndex] */ template<class T> void Merge(T *src, int startIndex, int middleIndex, int endIndex) { int n1 = middleIndex - startIndex + 1; int n2 = endIndex - middleIndex; //使L[n1],R[n2]成为新的数组 T *L = new T[n1 + 1]; T *R = new T[n2 + 1]; for (int i = 0; i < n1; i++) { L[i] = src[startIndex + i]; } for (int i = 0; i < n2; i++) { R[i] = src[middleIndex + i + 1]; } //哨兵牌,设置为该类型的最大值 L[n1] = numeric_limits<T>::max(); R[n2] = numeric_limits<T>::max(); int i = 0, j = 0; for (int k = startIndex; k <= endIndex; k++) { if (L[i] <= R[j]) { src[k] = L[i]; i++; }else{ src[k] = R[j]; j++; } } //删除动态分配的数组 delete[] L; delete[] R; } /* 归并排序 */ template<class T> void MergeSort(T *src, int startIndex, int endIndex) { if (startIndex < endIndex) { //这一部分相当于分治 int midIndex = (startIndex + endIndex) / 2; MergeSort(src, startIndex, midIndex); MergeSort(src, midIndex + 1, endIndex); //这一部分相当于合并 Merge(src, startIndex, midIndex, endIndex); } }
henry