首页 > 其他 > 详细

Divison and Recursion-MergeSort

时间:2016-03-19 17:57:42      阅读:207      评论:0      收藏:0      [点我收藏+]

#include<iostream>
using namespace std;

void DoMerge(int array[], int buff[], int begin, int middle, int end){
 int leftHalfBegin = begin;
    int leftHalfEnd   = middle;

 int rightHalfBegin = middle+1;
    int rightHalfEnd   = end;
    int index = begin;

 while (leftHalfBegin <= middle && rightHalfBegin <= end){
  if (array[leftHalfBegin] < array[rightHalfBegin]){
   buff[index] = array[leftHalfBegin];
   index++;
   leftHalfBegin++;
  }else{
   buff[index] = array[rightHalfBegin];
   index++;
   rightHalfBegin++;
  }
 }

 while (leftHalfBegin <= middle){
  buff[index++] = array[leftHalfBegin++];
 }
 while(rightHalfBegin <= end)
 {
  buff[index++] = array[rightHalfBegin++];
 }

 for(int i = begin; i<= end;i++){
  array[i] = buff[i];
 }

}
void MergeSort(int array[], int buff[], int begin, int end)
{
 int middle = (begin+end)/2;
 if (begin < end){
  MergeSort(array, buff, begin, middle);
  MergeSort(array, buff, middle + 1, end);
  DoMerge(array, buff, begin, middle, end);
 }
}

int main(){
 int array[6]={3,5,9,8,7,5};
 int buff[6];
    MergeSort(array, buff, 0, 5);
    for(int i =0;i<6;i++){cout<<array[i]<<endl;}

}

Divison and Recursion-MergeSort

原文:http://www.cnblogs.com/zhaodonglin/p/5295591.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!