merge sort

来源:互联网 发布:什么软件开发最有前途 编辑:程序博客网 时间:2024/05/20 03:06
void merge(int array[],int first,int position ,int last)
{
   int l1 = position - first +1;
   int l2 = last - position ;


   int* array1 = new int[l1+1];//using uniqure_ptr better;


   int* array2 = new int[l2+1];//using vector better;


   memcpy(array1,&array[first],sizeof(int)*l1);
   memcpy(array2,&array[position+1],sizeof(int)*l2);


   array1[l1] = numeric_limits<int>::max();//sentry simplify the program
   array2[l2] = numeric_limits<int>::max();


   int i = 0;
   int j = 0;


   for(int k = first; k<=last ; ++k)
   {
  if(array1[i]<=array2[j])
  {
array[k] = array1[i++];
  }
  else
  {
array[k] = array2[j++];
  }
   
   }


   delete [] array1 ;
   delete [] array2 ;




}


void merge_sort(int array[],int first,int last)
{
if(first<last)
{
int middle = first +( (last - first)>>1); //operator >> priority lower than +/- ,watch  overflowing
merge_sort(array,first,middle);
merge_sort(array,middle+1,last);
merge(array,first,middle,last);


}






}






//test



int _tmain(int argc, _TCHAR* argv[])
{


   int array[] = {5,3,6,8,4,9,5,1,81,63,96,6,4,6,87};
//insert_sort(array,array+14);
merge_sort(array,0,14);
for_each(array,array+14,[](int a){cout<<a<<" ";});
return 0;
}
原创粉丝点击