归并排序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

template <class T>
void
merge(T* array, int left, int mid, int right, T* temp)
{
  int i =left;
  int j =mid+1;
  int p=0;
  while(i<=mid && j <=right){
    if(array[i]>array[j]){
      temp[p++]=array[j++];
    }else{
      temp[p++]=array[i++];
    }
  }
  if(j<=right){
    memcpy(temp+p, array+j, sizeof(T)*(right-j+1));
  }else if(i<=mid){
    memcpy(temp+p, array+i, sizeof(T)*(mid-i+1));
  }
  memcpy(array+left, temp, sizeof(T)*(right-left+1));
}

template <class T>
void
mergesort(T* array, int left, int right, T* temp)
{
  if(left >= right)
    return;
  int mid = (left+right)/2;
  mergesort(array, left, mid, temp);
  mergesort(array, mid+1, right, temp);
  merge(array, left, mid, right, temp);
}

int
main()
{
  int array[10]={9,8,7,6,5,40,3,2,1,0};
  int temp[10];
  int len = sizeof(array)/sizeof(int);
  mergesort(array, 0, len, temp);
  for(int i=0; i<len; ++i){
    printf("%d ", array[i]);
  }
  printf("\n");
}

posted @ 2011-04-30 16:25  Richard Zhong  阅读(140)  评论(0编辑  收藏  举报