Merge operations on multiple ordered arrays

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.