#include <iostream>
using namespace std;
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<time.h>
typedef int elementType;
/*将两个有序的数组[start,mid],[mid+1,end]2路合并
注意:此中由于是[start,mid],[mid+1,end]
所以while循环中均需要加上等号。
*/
void merge(elementType* array,int start,int mid ,int end){
elementType * tempArray=(elementType*)malloc((end-start+1)*sizeof(elementType));
if(!tempArray) reutrn ;
int index1=start;
int index2=mid+1;
int temp=0;
while(index1<=mid&&index2<=end){
if(array[index1]<=array[index2]){
tempArray[temp++]=array[index1++];
}
else{
tempArray[temp++]=array[index2++];
}
}
while(index1<=mid){
tempArray[temp++]=array[index1++];
}
while(index2<=end){
tempArray[temp++]=array[index2++];
}
for(index1=start,temp=0;temp<end-start+1;temp++)
array[index1++]=tempArray[temp];
free(tempArray);
}
/*
注意归并排序:对数组不断的进行划分,知道数组中只有一个元素时,这个时候数组就是有序的。
所以注意递归结束条件:只有一个元素即start=end
所以递归结构体的执行条件是:start<end
数组的范围是[start,end ](左闭右闭)
*/
void mergeSort(elementType* array,int start,int end){
if(start<end){
int mid=(end-start)/2+start;
mergeSort(array,start ,mid);
/*[start , mid ]*/
mergeSort(array,mid+1,end);
/*[mid+1,end]*/
merge(array,start,mid,end);
}
}
/*
display the array
*/
void display(elementType * array ,int length){
cout<<endl<<"display the array "<<endl;
for(int i=0;i<length;i++)
cout<<array[i]<<" ";
cout<<endl;
}
int main()
{
int length=8;
int from=0;
int end=10;
elementType * array=(elementType*)malloc(length*sizeof(elementType));
if(!array) return 0;
srand(time(0));
for(int i=0;i<length;i++){
array[i]=rand()%(end-from+1)+from;
}
display(array,length);
cout<<endl<<"mergeSort the array"<<endl;
mergeSort(array,0,length-1);
display(array,length);
cout << "Hello world!" << endl;
free(array);
return 0;
}