#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<time.h>
#include<iostream>
using namespace std;
//
void PrintArr(int *pnArr, int nlen)
{
for (int i = 0; i < nlen; i++)
{
cout << pnArr[i] << endl;;
}
cout << endl;
}
//void Merge(int data[], int nLpos, int nRpos, int nRightEnd)
//{
// int i;
// int k = nLpos;
// int nLeftEnd = nRpos;
// int nTmpos = 0;
// int nLen = nRightEnd - nLpos + 1;
// //int *pnArr = (int *)malloc(sizeof(int)* nLen);
// int *pnArr = new int[nLen];
// ++nRpos;
//
// while (nLpos <= nLeftEnd && nRpos <= nRightEnd)
// {
// if (data[nLpos] <= data[nRpos])
// pnArr[nTmpos++] = data[nLpos++];
// else
// pnArr[nTmpos++] = data[nRpos++];
// }
// while (nLpos <= nLeftEnd)
// pnArr[nTmpos++] = data[nLpos++];
// while (nRpos <= nRightEnd)
// pnArr[nTmpos++] = data[nRpos++];
//
// nTmpos = 0;
// for (i = k; i <= nRightEnd; i++)
// data[i] = pnArr[nTmpos++];
//
// //free(pnArr);
// delete pnArr;
//}
//void MergeSort(int *pnArr, int nLeft, int nRight)
//{
// if (nLeft > nRight)
// return;
// if (nRight > nLeft)
// {
// int nMid = (nLeft + nRight) / 2;
// MergeSort(pnArr, nLeft, nMid);
// MergeSort(pnArr, nMid + 1, nRight);
// Merge(pnArr, nLeft, nMid, nRight);
// }
//}
void Merge(int arr[], int i, int j, int k)
{
int h = i; // 这一步是易错点 主要是记录arr数组刚开始排序的位置,在下面的赋值中可以用到
int nLen = k- i + 1;
int* tmep = new int[nLen];
int x = 0;
int start = i, end = k;
int nLeftEnd = j;
int Rbegin = j+1;
while (start <= nLeftEnd && Rbegin <= end)
{
if (arr[start] <= arr[Rbegin])
tmep[x++] = arr[start++];
else
tmep[x++] = arr[Rbegin++];
}
while (start <= nLeftEnd)
tmep[x++] = arr[start++];
while (Rbegin <= end)
tmep[x++] = arr[Rbegin++];
x = 0;
for (int j = i; j <= end; j++)// 把排好序的数组重新赋值给arr
arr[j] = tmep[x++];
delete tmep;
}
void MergeSort(int *arr, int start, int end)
{
if (start > end)
return;
if (end > start)
{
int middle = (start + end) / 2;
MergeSort(arr,start, middle);
MergeSort(arr, middle+1, end);
Merge(arr,start,middle,end);
}
}
int main()
{
srand(time(nullptr));
int nArr[10];
for (int i = 0; i < 10; i++)
nArr[i] = rand() % 100;
cout << "排序前:" << endl;
PrintArr(nArr, 10);
MergeSort(nArr, 0, 9);
cout << "排序后" <<endl;
PrintArr(nArr,10);
system("pause");
return 0;
}