/* file: merge_sort */
/* 1、if n = 1 done */
/* 2、divide:A[1..n/2] and A[n/2+1..n] */
/* 3、merge 2 sorted subarray */
#include<stdio.h>
#include <stdlib.h>
/*=====================================
Array: the array to be ordered
left :the left point of the array
mid : the middle point of the array
right: the right point of the array
Aux : an array used to storage
=======================================*/
void MergeArray(int* Array, int left, int mid, int right, int* Aux)
{
int i,j,k;
//copy the array to the aux, left subarray in order
for(i = mid + 1; i > left; i--)
Aux[i-1] = Array[i-1];
//copy the array to the aux, right subarray in reversed order
//so that i and j will meet at the middle of the array
for(j = mid; j < right; j++)
Aux[right+mid-j] = Array[j+1];
//merge the two subarrays
for(k = left; k <= right; k++)
if(Aux[j] < Aux[i])
Array[k] = Aux[j--];
else
Array[k] = Aux[i++];
}
/*=====================================
Array: the array to be ordered
left :the left point of the array
right: the right point of the array
Aux : an array used to storage
=======================================*/
void MergeSort(int* Array, int left,int right,int* Aux)
{
int mid = (left + right)/2;
if(left < right)
{
//sort the left subarray
MergeSort(Array,left,mid,Aux);
//sort the right subarray
MergeSort(Array,mid+1,right,Aux);
//merge the two sorted subarrays
MergeArray(Array,left,mid,right,Aux);
}
}
void main()
{
int n,i;
printf("Please input the length of Array<0:exit>:\n");
while(scanf("%d",&n),n)
{
//create two arrays of length n
int* Array = new int[n];
int* Aux = new int[n];
//get the input integers
printf("Please input %d integers:\n",n);
for(i = 0; i < n; i++)
scanf("%d",&Array[i]);
//use mergesort algorithom
MergeSort(Array,0,n-1,Aux);
//print the sorted array
printf("Sorted Array:\n");
for(i = 0; i < n; i++)
printf("%d ",Array[i]);
system("pause");
system("cls");
//delete the two arrays
delete[] Array;
delete[] Aux;
printf("Please input the length of Array<0:exit>:\n");
}
}
归并排序的特性:
(1)对N个元素的文件进行排序,它的运行时间与NlogN 成比例,与输入数据无关;
(2)如果使用的归并算法是稳定的,则归并排序是稳定的;
(3)归并排序使用与N成正比的额外内存空间;
Array
left mid right
i | j |
sorted | sorted |