void Merge(int *a, int s, int m, int e)
{
int ans = 0;
int anm = 0;
int lens = m - s + 1;
int lenm = e - m;
int* temp = new int[e - s + 1];
int i = 0;
while (ans<lens && anm<lenm)
{
temp[i] = a[s + ans] <= a[m + 1 + anm] ? a[s + ans++] : a[m + anm++ + 1];
i++;
}
if (ans < lens)
{
for (int j = 0; j < lens-ans; j++)
{
temp[i] = a[s+ j + ans];
i++;
}
}
if (anm < lenm)
{
for (int j = 0; j < lenm - anm; j++)
{
temp[i] = a[m + 1 + j + anm];
i++;
}
}
for (int i = 0; i < e - s + 1; i++)
{
a[s+i] = temp[i];
}
delete temp;
temp = NULL;
}
void MergeSort1(int *a, int p, int r)
{
if (p<r)
{
int q = (p + r) / 2;
MergeSort1(a, p, q);
MergeSort1(a, q + 1, r);
Merge(a, p, q, r);
}
}
int main()
{
int a[] = { 1, 2, 7, 4, 6, 6, 7, 8, 10, 4 };
MergeSort1(a, 0, sizeof(a) / sizeof(int)-1);
for (int i = 0; i < 10; i++)
{
cout<<(a[i])<<" ";
}
/*for (int i = 0; i < 10; i++)
{
cout << random_select(a, 0, 9, i+1) << endl;
}*/
//char str[] = "abcd";
//showString(str, 4);
return 0;
}
归并排序
最新推荐文章于 2018-07-26 15:39:43 发布