码迷,mamicode.com
首页 > 其他好文 > 详细

Divison and Recursion-MergeSort

时间:2016-03-19 17:58:17      阅读:147      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!