参考以下博文实现归并排序,在此记录,便于温习。
图解排序算法(四)之归并排序https://www.cnblogs.com/chengxiao/p/6194356.html
基本思路:(递归实现)
- 划分。将数组划分为两个长度较短的子片段,直到子片段中只有一个元素。
- 当数组不能往下划分时,开始回溯,反复将两个长度较短的有序段合并成一个有序段(采用三指针法进行合并),直到数组中只含一个有序段。
//归并排序算法
//2020-05-14
#include <iostream>
using namespace std;
void merge(int a[], int left, int mid, int right,int temp[])
{
int i = left, j = mid + 1;
int k = 0;
while (i <= mid && j <= right) //用临时数组temp暂存排序好的数组
{
if (a[i] <= a[j]) temp[k++] = a[i++];
else temp[k++] = a[j++];
}
while(i<=mid) temp[k++] = a[i++];
while(j<=right) temp[k++] = a[j++];
//将temp数组的值拷贝回原数组
k = 0;
while (left <= right) a[left++] = temp[k++];
}
void merge_sort(int a[], int left, int right,int temp[])
{
if (left < right)
{
int mid = (left + right) / 2;
merge_sort(a, left, mid, temp);
merge_sort(a, mid + 1, right, temp);
merge(a, left, mid, right, temp);
}
}
int main()
{
int len;
int array[100];
int temp[100]; //临时数组,避免频繁分配内存
cout << "输入排序数组的长度:";
while (cin >> len)
{
cout << "输入排序数组:";
for (int i = 0; i < len; ++i)
cin >> array[i];
//接下来开始排序
merge_sort(array, 0, len - 1, temp);
cout << "排序后输出:" << endl;
for (int i = 0; i < len; ++i)
cout << array[i] << ' ';
cout << endl;
cout << "输入排序数组的长度:";
}
return 0;
}