二路归并排序mergeSort代码实现_legend



#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值