一.归并排序
转载请附上链接:https://blog.csdn.net/qq_37978862/article/details/104675841
#include <iostream>
using namespace std;
#define MAX 100 //设置数组大小
#define END 65535 //设置超尾元素
int count; //得到比较的次数
//设置临时数组的空间大小
int L[MAX / 2 + 2], R[MAX / 2 + 2];
//分治
void merge(int a[], int left, int mid, int right)
{
//保存临时数组
int n1 = mid - left;
int n2 = right - mid;
//将原数组的值转移动临时数组中
for (int i = 0; i < n1; i++)
L[i] = a[i + left];
for (int i = 0; i < n2; i++)
R[i] = a[i + mid];
//设置超尾元素
L[n1] = R[n2] = END;
//比较并重新放入原数组
int i = 0,j = 0 ;
for(int k = left;k<right;k++)
{
count++;
if( L[i]<=R[j] )
a[k] = L[i++];
else
a[k] = R[j++];
}
}
//利用递归的思想重复比较
void merge_sort(int *a, int left, int right)
{
if (left + 1 < right)
{
int mid = (left + right) / 2;
merge_sort(a, mid, left);
merge_sort(a, mid, right);
merge(a, left, mid, right);
}
}
int main()
{
int n;
int a[MAX];
int left,right;
cin>>n;
for( int i = 0;i<n;i++)
{
cin>>a[i];
}
left = 0;
right = n;
merge_sort(a,left,right);
printf("****************\n");
for( int i = 0;i<n;i++)
{
cout<<a[i]<<endl;
}
}