重点算法--合并排序

#include<iostream>
using namespace std;
 
void merge(int left,int mid,int right,int a[],int b[])
{
  int i = 0;
  int cursor1 = left;
  int cursor2 = mid +1;
  while(cursor1 <= mid && cursor2 <= right)
  {
    if(a[cursor1] < a[cursor2])
    b[i++] = a[cursor1++];  
    else
    b[i++] = a[cursor2++]; 
  }

  while(cursor1<=mid)    b[i++] = a[cursor1++];  

  while(cursor2<=right) b[i++] = a[cursor2++];  

  for(int j = 0;j< i;j++)
      a[j + left] = b[j];
}

void mersort(int left,int right,int a[],int b[]){
    if(left<right)
    {
      int mid = (left + right)/2;
      mersort(left,mid,a,b);
      mersort(mid+1,right,a,b);///这个+1是如此的明智
      merge(left,mid,right,a,b);
    }
}

int main()
{
    int a[] = {1,5,4,3,2,6,7,4,1,6,7};
    int b[11] = {};
    mersort(0,10,a,b);
    for(int i = 0;i< 10;i++)
        cout<<a[i]<<" ";
}

 

posted on 2014-05-27 11:40  berkeleysong  阅读(206)  评论(0编辑  收藏  举报

导航