I’m trying to merge to sorted arrays into a third sorted array , but I can’t see
any way to do that in O(n) , only in O(n*n) .Am I wrong ? is there a way to do that in O(n) ?
Edit :
Actually the question is a little different :
I have 2 sorted skip lists and I want to merge them into a new sorted skip list ,without changing
the input (i.e. the two skip lists) .
I was thinking about :
-
put the lists in two arrays
-
merge the two arrays using MergeSort (this takes
O(n)runtime) -
build a new skip list from the sorted array …. // I’m not sure about its runtime
any ideas ?
Regards
You keep two loops going, and flip between each of them as you pull values from each ‘side’ into the 3rd array. if arr1’s values are less than the current arr2, then stuff arr1’s values into arr3 until you hit equality or go ‘bigger’, then you flip the process and start pulling values out of arr2. And then just keep bouncing back/forth until there’s nothing left in either source array.
Comes out to O(n+m), aka O(n).