#include <stdio.h>
#include <stdlib.h>
void mergearray(int a[], int first, int mid, int last, int temp[]);
void mergesort(int a[], int first, int last, int temp[]);
bool MergeSort(int a[], int n);
int main()
{
int a[6] = { 4 ,5, 6, 1, 2, 3 };
if (!MergeSort(a, 6))
{
exit(0);
}
for (int i = 0; i < 6; i++)
{
printf("%d", a[i]);
}
return 0;
}
void mergearray(int a[], int first,int mid, int last, int temp[])
{
int i = first;
int j = mid + 1;
int k = first;
while(i<=mid && j<=last)
{
if (a[i] < a[j])
{
temp[k++] = a[i++];
}
else
temp[k++] = a[j++];
}
while (i < first)
{
temp[k++] = a[i++];
}
while (j < last)
{
temp[k++] = a[j++];
}
for (int m = first; m <= last;)
{
a[m++] = temp[m++];
}
}
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;
}
else
{
mergesort(a, 0, n - 1, p);
delete[] p;
return true;
}
}

uj5u.com熱心網友回復:
我已經知道哪里錯了。。。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/49211.html
標籤:新手樂園
