#include<stdio.h>
void merge_sort(int *A,int p,int r);
void merge(int *A,int p,int q,int r);
int main(){
int array[5];
int num;
printf("请输入数组长度:\n");
scanf("%d",&num);
printf("请输入元素:\n");
for(int i=0;i<num;i++)
scanf("%d",&array[i]);
merge_sort(array,0,num-1);
for(int i=0;i<num;i++)
printf("%d",array[i]);
return 0;
}
void merge_sort(int *A,int p,int r){
if(p<r){
int q=(p+r)/2;
merge_sort(A,p,q);
merge_sort(A,q+1,r);
merge(A,p,q,r);
}
}
void merge(int *A,int p,int q,int r){
int n1=q-p+1;
int n2=r-q;
int L[n1-1],R[n2-1];
for(int i=0;i<n1-1;i++)
L[i]=A[p+i];
for(int j=0;j<n2-1;j++)
R[j]=A[q-1+j];
int key=0;
L[n1]=key;
R[n2]=key;
int i=0,j=0;
for(int k=0;k<r-p;k++){
if(L[i]<=R[j]){
A[k]=L[i];
i++;
}
else{
A[k]=R[j];
j++;
}
}
}
归并排序,它采取分而治之的策略,将两个已经排序的序列合并成一个序列的操作。
时间复杂度是Θ(nlgn),优于插入排序算法。
算法描述
1) 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
2) 设定两个指针,最初位置分别为两个已经排序序列的起始位置
3) 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
4) 重复步骤3直到某一指针达到序列尾
5) 将另一序列剩下的所有元素直接复制到合并序列尾
特点:归并排序是稳定的排序.即相等的元素的顺序不会改变, 速度仅次于快速排序,但较稳定。
void merge(int *array,const int first, const int mid, const int last)
{
int i,index;
int first1,last1;
int first2,last2;
int *tmp;
tmp = (int *)malloc((last-first+1)*sizeof(int));
if( tmp == NULL )
return;
first1 = first;
last1 = mid;
first2 = mid+1;
last2 = last;
index = 0;
while( (first1 <= last1) && (first2 <= last2) )
{
if( array[first1] < array[first2] )
{
tmp[index++] = array[first1];
first1++;
}
else{
tmp[index++] = array[first2];
first2++;
}
}
while( first1 <= last1 )
{
tmp[index++] = array[first1++];
}
while( first2 <= last2 )
{
tmp[index++] = array[first2++];
}
for( i=0; i<(last-first+1); i++)
{
array[first+i] = tmp[i];
}
free(tmp);
}
/*** 使用递归实现 ***/
void merge_sort(int *array, const int first, const int last)
{
int mid=0;
if(first < last)
{
mid=(first+last)/2;
merge_sort(array,first,mid);
merge_sort(array,mid+1,last);
merge(array,first,mid,last);
display_array(first, last-first+1, array+first);
}
}
/*** 使用迭代实现 ***/
/*
void merge_sort(int *list, const int first, const int last)
{
int len= last-first+1;
int left_min,left_max;
int right_min,right_max;
int index;
int i;
int *tmp;
tmp = (int *)malloc(sizeof(int)*len);
if( tmp == NULL || len <= 0 )
return;
for( i = 1; i < len; i *= 2 )
{
for( left_min = 0; left_min < len - i; left_min = right_max)
{
int j;
right_min = left_max = left_min + i;
right_max = left_max + i;
j = left_min;
if ( right_max > len )
right_max = len;
index = 0;
while( left_min < left_max && right_min < right_max )
{
tmp[index++] = (list[left_min] > list[right_min] ? list[right_min++] : list[left_min++]);
}
while( left_min < left_max )
{
list[--right_min] = list[--left_max];
}
while( index > 0 )
{
list[--right_min] = tmp[--index];
}
display_array(j,i*2,list+j);
}
}
free(tmp);
}
*/