思想:
接下来用图分解:
19,97,9,17,1,8
第一次排序完成
比谁的对头小,谁小放前面
把剩下的全部依次移动到数组,就剩余一个数组,如下,这个就是有序的。
接下来看看代码:
void mergety(int a[], int left, int nmid, int nright, int ntemp[])
{
int i = left;
int j = nmid + 1;
int t = 0;
//主要思想就是对比谁的头小,谁小就放谁。
while (i <= nmid&&j <= nright)
{
if (a[i] <= a[j])
{
ntemp[t++] = a[i++];
}
else
{
ntemp[t++] = a[j++];
}
}
//将左边剩余的全部拷贝到temp中
while (i <= nmid)
{
ntemp[t++] = a[i++];
}
//将右边剩余的全部拷贝到temp中
while (j <= nright)
{
ntemp[t++] = a[j++];
}
//将temp中的元素赋值到a中,其实说白了还是在原地排序。
t = 0;
while (left <= nright)
{
a[left++] = ntemp[t];
t++;
}
}
void sortex(int arr[], int left, int right, int temp[])
{
if (left < right)
{
int mid = (left + right) / 2;
sortex(arr, left, mid, temp);//左边归并排序,使得左子序列有序
sortex(arr, mid + 1, right, temp);//右边归并排序,使得右子序列有序
mergety(arr, left, mid, right, temp);//将两个有序子数组合并操作
}
}
void sort1(int arr[], int nlen)
{
int *temp = new int[nlen];//在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间
sortex(arr, 0, nlen - 1, temp);
delete temp;
temp = NULL;
}
int main()
{
int a[] = {
1, 3, 5, 7, 22, 9, 2, 4, 6, 8 };
int nlen = sizeof(a) / sizeof(a[0]);
cout << "原始数组1:\n";
for (int i = 0; i < nlen;i++)
{
cout << a[i] << " ";
}
cout << "\n排序后:\n";
sort1(a, nlen);
for (int i = 0; i < nlen; i++)
{
cout << a[i] << " ";
}
cout << "\n原始数组2:\n";
int b[] = {
19, 97, 9, 17, 1, 8 };
nlen = sizeof(b) / sizeof(b[0]);
for (int i = 0; i < nlen; i++)
{
cout << b[i] << " ";
}
cout << "\n排序后:\n";
sort1(b, nlen);
for (int i = 0; i < nlen; i++)
{
cout << b[i] << " ";
}
system("pause");
return 0;
}
结果:
归并排序的最好,最坏,平均时间复杂度均为O(nlogn)。
转载:https://blog.csdn.net/FairLikeSnow/article/details/112973812
查看评论