C++实现简单的合并算法模板


复制内容到剪贴板

代码:
/**
* project: merge template
* author:billhoo
* date: 2012年3月6日
*/
#pragma once
#ifndef _MERGE_H
#define _MERGE_H

#include  //iterator_trais

template
void merge(Iterator beg, Iterator middle, Iterator end){
  typedef typename std::iterator_traits::value_type val_t;
  typedef typename std::iterator_traits::difference_type iterdiff_t;

  const iterdiff_t leftArrLength = std::distance(beg, middle);
  const iterdiff_t rightArrLength = std::distance(middle, end);
  val_t *leftArr = new val_t[leftArrLength];
  val_t *rightArr = new val_t[rightArrLength];

  //copy left and right subsequence into new array respectively
  std::copy(beg, middle, leftArr);
  std::copy(middle, end, rightArr);
  
  Iterator index = beg;
  iterdiff_t leftArrIdx = 0;
  iterdiff_t rightArrIdx = 0;

  //do merge
  while(leftArrLength > leftArrIdx && rightArrLength > rightArrIdx){
    if(Comp()(leftArr[leftArrIdx], rightArr[rightArrIdx]))
      *index++ = leftArr[leftArrIdx++];
    else
      *index++ = rightArr[rightArrIdx++];
  }// end of while

  if(leftArrIdx < leftArrLength)
    std::copy(leftArr + leftArrIdx, leftArr + leftArrLength, index);
  else
    std::copy(rightArr + rightArrIdx, rightArr + rightArrLength, index);

  delete [] leftArr;
  delete [] rightArr;
}// end of merge

#endif // _MERGE_H

/**
* author:billhoo
* date: 2012年3月6日
*/
#include
#include

#include"merge.h"  //merge
#include"display_array.h"  //displayArr

using std::cout;
using std::endl;
using std::list;

int main(int argc, char **argv){
  int intArr[ ] = {1,2,5,8,9,0,3,4,5,7};
  int *intArrEnd = intArr + sizeof(intArr) / sizeof(*intArr);
  
  list intList(intArr, intArrEnd);

  cout<<"ints array merge..."<   displayArr(intArr, intArr + 10);
  merge>(intArr, intArr + 5, intArrEnd);
  displayArr(intArr, intArr + 10);

  list::iterator middle = intList.begin();
  std::advance(middle, 5);
  cout<<"\nints list merge..."<   displayArr(intList.begin(), intList.end());
  merge::iterator, std::less>(intList.begin(), middle, intList.end());
  displayArr(intList.begin(), intList.end());

  return EXIT_SUCCESS;
}