码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序方法

时间:2015-09-17 21:31:19      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:


#include <iostream>
using namespace std;

void mergearray(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;

while (i <= m && j <= n)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}

while (i <= m)
temp[k++] = a[i++];

while (j <= n)
temp[k++] = a[j++];

for (i = 0; i < k; i++)
a[first + i] = temp[i];
}
void mergesort(int a[], int first, int last, int temp[])
{
if (first < last)
{
int mid = (first + last) / 2;
mergesort(a, first, mid, temp); //左边有序
mergesort(a, mid + 1, last, temp); //右边有序
mergearray(a, first, mid, last, temp); //再将二个有序数列合并
}
}

bool MergeSort(int a[], int n)
{
int *p = new int[n];
if (p == NULL)
return false;
mergesort(a, 0, n - 1, p);
delete[] p;
return true;
}


int main()
{
int a[10] = { 3, 2, 1, 4, 5, 7, 6, 9, 8, 10 };
MergeSort(a, 10);
for (int i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
}

归并排序方法

标签:

原文地址:http://www.cnblogs.com/wll-zju/p/4817538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!