归并算法代码
#include <iostream>
using namespace std;
void Merger(int32_t numList[], int32_t first, int32_t mid, int32_t last) {
int32_t tmpList[13];
auto indexA = first;
auto indexB = mid + 1;
auto index = 0;
//在没有比较完两个子标的情况下,比较 numList[indexA]和numList[indexB]
//将其中小的放到临时变量tmpList中
while (indexA <= mid && indexB <= last) {
if (numList[indexA] < numList[indexB]) {
tmpList[index++] = numList[indexA];
indexA++;
} else {
tmpList[index++] = numList[indexB];
indexB++;
}
}
//复制没有比较完子表中的元素
while (indexA <= mid) {
tmpList[index++] = numList[indexA];
indexA++;
}
while (indexB <= last) {
tmpList[index++] = numList[indexB];
indexB++;
}
for (auto i = 0; i < index; i++) {
numList[first + i] = tmpList[i];
}
}
void MergerSort(int32_t numList[], int32_t first, int32_t last) {
if (first < last) {
auto mid = (first + last) / 2;
MergerSort(numList, first, mid);
MergerSort(numList, mid + 1, last);
Merger(numList, first, mid, last);
}
}
void main() {
int32_t numList[] = { 31, 41, 59, 26, 48, 58, 12, 5, 90, 10, 9, 6, 45};
int32_t count = sizeof(numList) / sizeof(numList[0]);
MergerSort(numList, 0, count-1);
for (auto num : numList) {
std::cout << num << " ";
}
std::cout << std::endl;
}
返回排序算法分析总结
参考文章:递归算法学习系列二(归并排序)