// 归并排序,mergeSort
// O(n*logn),稳定
#include <cstdio>
void merge(int arr[], int l, int mid, int r);
void mergeSort(int arr[], int l, int r)
{
if(l < r)
{
int mid = (l + r)/2;
mergeSort(arr, l, mid);
mergeSort(arr, mid+1, r);
merge(arr, l, mid, r);
}
}
void merge(int arr[], int l, int mid, int r)
{
int temp[r-l+1];
int i = l, j = mid+1, t = 0;
while(i <= mid && j <= r)
{
if(arr[i] <= arr[j])
temp[t++] = arr[i++];
else
temp[t++] = arr[j++];
}
while(i <= mid)
temp[t++] = arr[i++];
while(j <= r)
temp[t++] = arr[j++];
t = 0;
while(l <= r)
arr[l++] = temp[t++];
}
int main()
{
int arr[] = {1,3,4,5,2,6,9,7,8,0};
int n = sizeof(arr)/sizeof(arr[0]);
mergeSort(arr, 0, n);
for(int i = 0; i < n; i++)
printf("%d ",arr[i]);
return 0;
}
// 思路:先分而排序,再按序合并 (1)把初始序列分组,递归解决 (2)分别在各分组序列内完成排序
// (3)把各分组序列合并 (4)按排序方式把分组中数据合并
归并排序,mergeSort
最新推荐文章于 2022-02-11 03:27:44 发布