算法练习一 合并排序

 

int _tmain(int argc, _TCHAR* argv[]) { int num = 10; cout << "请输入需要排序数组的长度,数组将随机生成:" <<endl; cin >> num; // 随机生成N个int型元素的数组 int* arry = new int[num]; srand( (int)time(0) ); for ( int x=0; x<num; x++ ) { arry[x] = random(10000); cout << arry[x] << endl; } // 调用MergeSort方法 MergeSort( arry, 0, num-1 ); cout << "After sort "<< endl; for( int i=0; i<num; i++ ) { cout << arry[i] << "/t"; } delete[] arry; system("pause"); return 0; } /** MergeSort: 递归调用自身,分治法 @start: from Zero. @end: the length of Array */ void MergeSort(int Arry[], int start, int end) { if ( start < 0 || end <=0) { return; } if ( start < end ) { int mid = ( end + start ) / 2; MergeSort( Arry, start, mid ); MergeSort( Arry, mid + 1, end ); Merge(Arry, start, mid, end ); } } /* */ void Merge(int arry[], int st, int mid, int end) { int len1 = mid - st + 1; // 第一个元素需要 int len2 = end - mid; int* ary1 = new int[len1]; int* ary2 = new int[len2]; //合并数组 //cout << "合并数组" << "st=" << st << "mid="<< mid << "end=" << end << endl; for ( int i=0; i<len1; i++) { ary1[ i ] = arry[ st + i ]; //cout << ary1[i] << "/t"; } for ( int j=0; j<len2; j++) { ary2[ j ] = arry[ mid + 1 + j ]; //cout << ary2[j] << "/t"; } //cout << endl; //cout << "局部合并结果:" << endl; int i, j; i = 0; j = 0; for ( int n=0; n<(end-st+1); n++) // { if ( i<len1 && j<len2) { if ( ary1[i] < ary2[j] ) { arry[ n+st ] = ary1[i]; i++; } else { arry[ n+st ] = ary2[j]; j++; } } else { if ( i >= len1 ) { arry[ n+st ] = ary2[j]; j++; //cout << arry[ n+st ] << endl; continue; } if ( j >= len2 ) { arry[ n+st ] = ary1[i]; i++; //cout << arry[ n+st ] << endl; continue; } } //cout << arry[ n+st ] << endl; }//end for //cout << endl; delete[] ary1; delete[] ary2; } 

 

你可能感兴趣的:(算法练习一 合并排序)