Work has encountered a number of sequential chain merge operations, here to record the solution. Convenient for subsequent use.
Merge methods are listed in 2 ways:
(1) heap sort, or victory tree. Reduce the number of comparisons. High efficiency, difficult to achieve.
(2) Common method, need to compare each time. The implementation is simple, generally use this can.
The following code is an ordinary method that supports the merging of multiple sequential arrays.
#include <stdio.h>#include<climits>#include<vector>structnodelist{int*val;//array of values for saving data intNum//Number of data intCurr//Subscript that is currently being countedNodeList (intn): num (n), Curr (0) {Val=New int[n]; } ~NodeList () {if(val) {Delete[] Val; Val=NULL; } } };voidPrint_sort (std::vector<nodelist*>ver) { intLen =0; intMin_val =0; intMin_idx =-1; //multiple sequential arrays for merging operations while(len = ver.size ()) >0) {Min_val=Int_max; Min_idx= -1; //Select the minimum value for the current turn for(inti =0; i < Len; ++i) { if(Ver[i]->curr >= ver[i]->num) {Ver.erase (Ver.begin ()+i); Break; } intTmp_val = ver[i]->val[ver[i]->Curr]; if(Tmp_val <=min_val) {Min_val=Tmp_val; Min_idx=i; } } //Print if(Min_idx! =-1) {printf ("%d\n", Min_val); + + (ver[min_idx]->Curr); } }}intMain () {//New ordered ArrayNodeList A (2); a.val[0] =3; a.val[1] =4; NodeList B (3); b.val[0] =1; b.val[1] =3; b.val[2] =5; NodeList C (2); c.val[0] =4; c.val[1] =6; //building an ordered array listStd::vector<nodelist*>ver; Ver.push_back (&a); Ver.push_back (&b); Ver.push_back (&c); //Sort PrintPrint_sort (ver); return 0;}
Merge operations on multiple ordered arrays