归并排序
归并排序,是创建在归并操作上的一种有效的排序算法,效率为{\displaystyle O(n\log n)}。该算法是采用分治法的一个非常典型的应用,且各层分治递归可以同时进行。
基本思路就是将数组分成两组A,B,(如果这二组组内的数据都是有序的,那么就可以很方便的将这二组数据进行排序),然后将A,B组各自再分成两组。依次类推,当分出来的小组只有一个数据时,可以认为这个小组组内已经达到了有序,然后再合并相邻的二个小组就可以了。这样通过先递归的分解数列,再合并数列就完成了排序。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxx=505;
const int INF=1e9;
const int MOD=1e8;
void mergearray(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= m)
temp[k++] = a[i++];
while (j <= n)
temp[k++] = a[j++];
for (i = 0; i < k; i++)
a[first + i] = temp[i];
}
void mergesort(int a[], int first, int last, int temp[])
{
if (first < last)
{
int mid = (first + last) / 2;
mergesort(a, first, mid, temp); //左边有序
mergesort(a, mid + 1, last, temp); //右边有序
mergearray(a, first, mid, last, temp); //将二个有序数列合并
}
}
int main()
{
int temp[maxx];
int a[maxx]={3,5,6,4,2,7,8};
int len=7;
mergesort(a, 0, len - 1, temp);
for(int i=0; i<7; i++){
cout<<a[i]<<" ";
}
return 0;
}

浙公网安备 33010602011771号