C++实现归并排序
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现归并排序相关的知识,希望对你有一定的参考价值。
代码如下:
#include <iostream>
using namespace std;
void Merge(int a[], int mid, int low, int high);
void MergeSort(int a[], int low, int high)
{
if (low < high)
{
int mid = (low + high) >> 1;
MergeSort(a, low, mid);
MergeSort(a, mid + 1, high);
Merge(a, mid, low, high);
}
}
void Merge(int a[], int mid, int low, int high)
{
int i = low;
int j = mid + 1;
int k = 0;
int *w = new int[high - low + 1];
while (i <= mid && j <= high)
{
if (a[i] < a[j]) w[k++] = a[i++];
else w[k++] = a[j++];
}
while (i <= mid) w[k++] = a[i++];
while (j <= high) w[k++] = a[j++];
for (int i = low, j = 0; i <= high; i++, j++) a[i] = w[j];
delete[] w;
}
int main()
{
int a[] = { 12,3253,2414,1233,45,45432,34,1242,1567,123,5543,242,34,123,123 };
MergeSort(a, 0, 15 - 1);
for (int i = 0; i < 15; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
以上是关于C++实现归并排序的主要内容,如果未能解决你的问题,请参考以下文章