merge sorted arrays
We have two sorted array. Without using additional memory we need to merge these two arrays(sec开发者_如何学Pythonond array is having more space for merging). Output should return through second array
Assuming the addtional space is at the end of the second array, simply start merging from the end of the arrays. Use two indices i1
and i2
pointing at the current positions in the arrays and an index i
pointing to the current position in the merged array.
Initialise
i
,i1
andi2
to point to the last items of the respective arrays.Iterate: Write the maximum of
a1[i1]
anda2[i2]
toa2[i]
and adjust the indices (i.e. decreasei
and the index of the array holding the bigger value).
精彩评论