merge-sort(合并排序)

#ifndef _MERGE_H_ #define _MERGE_H_ template< class T > void merge( T* lpFinal, int iStart, int iMid, int iEnd ) { int n1 = iMid - iStart + 1; int n2 = iEnd - iMid; T * lpFore = new T[ n1 ]; T * lpRear = new T[ n2 ]; //拆分出的子数组 for( int index = 0; index < n1; ++index ) { lpFore[ index ] = lpFinal[ iStart + index ]; } for( int index = 0; index < n2; ++index ) { lpRear[ index ] = lpFinal[ iMid + index + 1 ]; } //数组末尾不使用哨兵元素 int k = iStart;//结果数组计数 int i = 0;//fore数组计数 int j = 0;//rear数组计数 for( ; k <= iEnd ; ++k ) { if( lpFore[ i ] <= lpRear[ j ] ) { lpFinal[ k ] = lpFore[ i ]; if( ++i == n1 ) { ++k; for( ;j < n2; ++j, ++k ) { lpFinal[ k ] = lpRear[ j ]; } break; } } else { lpFinal[ k ] = lpRear[ j ]; if( ++j == n2 ) { ++k; for( ;i < n1; ++i, ++k ) { lpFinal[ k ] = lpFore[ i ]; } break; } } } delete[] lpFore; delete[] lpRear; } #endif

#ifndef _MERGESORT_H_ #define _MERGESORT_H_ #include"merge.h" template< class T > void mergesort( T* lpFinal, int iStart, int iEnd ) { if( iEnd > iStart ) { int iMid = ( iStart + iEnd ) / 2; mergesort( lpFinal, iStart, iMid ); mergesort( lpFinal, iMid + 1, iEnd ); merge( lpFinal, iStart, iMid, iEnd ); } } #endif

#include<iostream> using namespace std; #include<conio.h> #include"mergesort.h" int main() { int a[ 8 ] ={ 2, 89, 56, 45, 77, 4, 6, 5 }; for( int i = 0; i < 8; ++i ) { cout<<a[ i ]<<" "; } cout<<endl; mergesort( a, 0, 7 ); for( int i = 0; i < 8; ++i ) { cout<<a[ i ]<<" "; } getch(); return 0; }

你可能感兴趣的:(merge-sort(合并排序))