c# - How to create a sorting algorithm for this special array with linear time? -
i've got tricky question can't seem figure out. have array length n+m.
the array made out of n numbers sorted, m numbers sorted. example:
2 5 8 11 15 17 19 3 4 9 10
then n=7 , m=4.
i need sort whole array in o(n)
timewise , not usage of arrays / lists.
you need perform last stage of merge sort merge 2 sorted lists/arrays. added complication want o(1) memory usage. can done follows.
if have arrays of size n + m
- start array
i
[0 .. n) ,j
[n .. n+m) - if first array lower, leave it.
- if second array lower, swap second array.
- now first array in 2 places [n..j) [i..m)
in short have 3 arrays
- [0..i+j) - sorted portion.
- [n..j) [i+j..n) first array
- [j..n+m) second array.
as progress i+j
end in 1 pass , have sorted array.
Comments
Post a Comment