c++ - Merge sorted arrays - Efficient solution -
goal here merge multiple arrays sorted resultant array.
i've written following solution , wondering if there way improve solution
/* goal merge sorted arrays */ void mergeall(const vector< vector<int> >& listofintegers, vector<int>& result) { int totalnumbers = listofintegers.size(); vector<int> curpos; int currow = 0 , minelement , foundminat = 0; curpos.reserve(totalnumbers); // set current position travered 0 in array elements ( int = 0; < totalnumbers; ++i) { curpos.push_back(0); } ( ; ; ) { /* find first minimum first element in array hasn't been traversed */ ( currow = 0 ; currow < totalnumbers ; ++currow) { if ( curpos[currow] < listofintegers[currow].size() ) { minelement = listofintegers[currow][curpos[currow] ]; foundminat = currow; break; } } /* if elements traversed in arrays, no further work needs done */ if ( !(currow < totalnumbers ) ) break; /* traverse each of array , find out first available minimum value */ ( ;currow < totalnumbers; ++currow) { if ( listofintegers[currow][curpos[currow] ] < minelement ) { minelement = listofintegers[currow][curpos[currow] ]; foundminat = currow; } } /* store minimum resultant array , increment element traversed */ result.push_back(minelement); ++curpos[foundminat]; } }
the corresponding main goes this.
int main() { vector< vector<int> > myint; vector<int> result; myint.push_back(vector<int>() ); myint.push_back(vector<int>() ); myint.push_back(vector<int>() ); myint[0].push_back(10); myint[0].push_back(12); myint[0].push_back(15); myint[1].push_back(20); myint[1].push_back(21); myint[1].push_back(22); myint[2].push_back(14); myint[2].push_back(17); myint[2].push_back(30); mergeall(myint,result); ( int = 0; < result.size() ; ++i) { cout << result[i] << endl; } }
you can generalize merge sort algorithm , work multiple pointers. initially, of them pointing beginning of each array. maintain these pointers sorted (by values point to) in priority queue. in each step, remove smallest element in heap in o(log n)
(n number of arrays). output element pointed extracted pointer. increment pointer in 1 position , if didn't reach end of array, reinsert in priority queue in o(log n)
. proceed way until heap not empty. if there total of m elements, complexity o(m log n)
. elements output in sorted order way.
Comments
Post a Comment