归并排序

Posted liangyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序相关的知识,希望对你有一定的参考价值。


#include<iostream>
#include<assert.h>
using namespace std;


int temp[20];

void domerge(int*a, int left, int right){

 

for (int i = left; i <= right; i++)
temp[i] = a[i];


int low = left;
int mid = (left + right) / 2;
int high = (left + right) / 2 + 1;

for (int i = left; i <= right; i++){

if (low>mid){
a[i] = temp[high++];
}
else if (high>right){
a[i] = temp[low++];
}
else if (temp[low]<temp[high]){
a[i] = temp[low++];
}
else {
a[i] = temp[high++];
}


}


}
void merge(int*a, int left, int right){
if (left >= right) return;
int mid = (left + right) / 2;

merge(a, left, mid);
merge(a, mid + 1, right);
domerge(a, left, right);

}


int main(){
int temp[12] = { 81, 4, 6, 2, 33, 6, 1, 6, 3, 4, 3, 0 };
merge(temp, 0, 11);

for (int i = 0; i < 12; i++)
cout << temp[i] << " ";
getchar();
return 0;
}

以上是关于归并排序的主要内容,如果未能解决你的问题,请参考以下文章

常见排序算法之归并排序——归并排序

归并排序

归并排序(递归非递归以及自然归并排序)算法总结

排序算法——归并排序

归并排序(逆序数问题)详解

归并排序及其应用场景