求二路归并排序算法的非递归实现
求二路归并排序算法的非递归实现,一点思路都没有,求高手指点~
程序代码:
void mergeImproved( vector<Comparable> &a ) { int size = a.size(); vector<Comparable> b( size ); // 唯一的临时数组 int maxLayer = 1; for ( int items = 2; items < size; items *= 2, ++maxLayer ); // for each layer, perform merge sort. for ( int curLayer = 0, items = 0; curLayer < maxLayer; ++curLayer ) { items = int( pow( double( 2 ), double( curLayer ) ) );//功能:pow(x,y)返回x的y次幂 // decide which array of a and b is input or output vector<Comparable> &in = ( curLayer % 2 == 0 ) ? a : b; vector<Comparable> &out = ( curLayer % 2 == 0 ) ? b : a; // for each left and right sub arrays on the block for ( int index = 0; index < size; index += ( 2 * items ) ) { // fix the left array's first and last indices int first1 = index; int last1 = ( first1 + items - 1 < size - 1 ) ? first1 + items - 1 : size - 1; // fix the right array's first and last indices int first2 = ( last1 + 1 < size - 1 ) ? last1 + 1 : size - 1; int last2 = (first2 + items - 1 < size - 1 ) ? first2 + items - 1 : size - 1; // now merge them in one block int outIx = first1; for ( ; first1 <= last1 && first2 <= last2; ++outIx ) out[outIx] = ( in[first1] < in[first2] ) ? in[first1++] : in[first2++]; for ( ; first1 <= last1; ++first1, ++outIx ) out[outIx] = in[first1]; for ( ; first2 <= last2; ++first2, ++outIx ) out[outIx] = in[first2]; } } // in case the sort items are in the temporary array if ( maxLayer % 2 == 1 ) a = b; // copy them back to the original }