下面代码仅供本人复习数据结构所用,实用性N低,各位飘过吧~~哈哈:>
// // C++ 模版技术实现归并排序. // #include <cstdlib> #include <cstring> #include <iostream> #include <stdexcept> // // 归并操作. // template <typename T> void merge(T *array, const size_t low, const size_t mid, const size_t high) { if (NULL == array) { throw std::invalid_argument("参数 array 为 NULL."); } // 辅组空间. T *tempArray = new T[high - low + 1]; size_t i, begin1, begin2; for (i = 0, begin1 = low, begin2 = mid + 1; begin1 <= mid && begin2 <= high; ++i) { tempArray[i] = array[begin1] < array[begin2] ? array[begin1++] : array[begin2++]; } while (begin1 <= mid) { tempArray[i++] = array[begin1++]; } while (begin2 <= high) { tempArray[i++] = array[begin2++]; } for (i = 0; i < high - low + 1; ++i) { array[low + i] = tempArray[i]; } delete[] tempArray; } // // 归并排序. // template <typename T> void mergeSort(T *array, const size_t first, const size_t last) { if (first < last) { size_t mid = (first + last) / 2; mergeSort(array, first, mid); mergeSort(array, mid + 1, last); merge(array, first, mid, last); } } // // 测试 // int main(void) { char szTest[] = "Merge sort algorithm test case !"; int iarrTest[] = {23, 12, 2, 123, 72, 35, 49, 51, 83, 94, 65}; const size_t INT_ARR_SIZE = sizeof(iarrTest) / sizeof(iarrTest[0]); mergeSort(szTest, 0, strlen(szTest) - 1); mergeSort(iarrTest, 0, INT_ARR_SIZE - 1); std::cout << szTest << std::endl; for (size_t i = 0; i < INT_ARR_SIZE; ++i) { std::cout << iarrTest[i] << " "; } std::cout << std::endl; return EXIT_SUCCESS; }