K-way merge algorithm: Difference between revisions

Content deleted Content added
Line 6:
 
=== Example<ref>{{Cite web|title = ALGORITHM TO MERGE SORTED ARRAYS (Java, C++) {{!}} Algorithms and Data Structures|url = http://www.algolist.net/Algorithms/Merge/Sorted_arrays|website = www.algolist.net|accessdate = 2015-11-19}}</ref> ===
Assume, that we have two arrays A[0..mp-1] and B[0..nq-1] that are sorted in ascendingnon-decreasing order and we want to merge them into an array C[0..m+n-1] with the same order.
 
# Introduce read-indices '''i''', '''j''' to traverse arrays A and B, accordingly. Introduce write-index '''k''' to store position of the first free cell in the resulting array. InitiallyInitialize '''i''' =, '''j''', =and '''k''' =with 0.
# At each step: if both indices are in range ('''i''' < mp and '''j''' < nq), choose minimum of (A['''i'''], B['''j''']) and write it to C['''k''']. If A['''i'''] and B['''j'''] are the same then pick either. Otherwise go to step 4.
# Increase '''k''' andby indexone. ofFurther, thedepending array,on algorithmwhich locatedlist's minimalelement valuewas atsmaller, either increase '''i''' or '''j''' by one. RepeatGoto step 2.
# Copy the restremaining values from the array, whichwhose indexend iswas stillnot inyet range, to the resulting arrayreached.
 
=== Applying 2-Way Merge when k > 2 ===