Qualcomm Interview Question
Software Engineer / Developersa form of merge sort is better.
it can be done in O(n+m*log(m)), which is significantly better then O(n*m) or O(n*log(n)):
1. run over the array, O(n)
1.1. every time encountering unsorted element, move it to array2 (array size will be m).
1.2. since you get gaps, move each sorted element k cells back (where k is the number of dislocated elements), which will leave m empty cells in the end of the array.
2. sort array2 in O(m*log(m))
3. merge sort the two sorted arrays from end to start (for each element choose the better and put it in the end of array1). O(m+n)
My first thought was indeed Insertion sort...
But for every displaced number you insert, you'd have to 'shift' the entire sub-array that is larger than the displaced number.
Obviously smells like O(m.n) solution at 'best', n being total numbers (100000), m being displaced numbers (50).
Can't we do better than that, like O(n)?
--- I guess NOT LOL...
For 1000 elements, quick sort is also considered because it might reduce swapping elements overhead in selection sort, but it takes more space.
insertion sort is the answer, the order is O(n+d), d number of inversions, in this case 50, so it's order O(n).
# of inversions ranges from 50 to 50*n, since we could have a list like [11,12...100, 10,9,...1] where the final 10 elements are the unsorted part and the first 90 elements are the sorted part. In this case all the final 10 elements are inversions for the first 90 elements. Depending on the actual number of inversions/merge sort constants, it might actually be better to merge sort.
merge sort worst case => n log n = 1,000,000
insertion sort worst case => 50*n = 5,000,000
Insertion sort works in linear time....because in the worst case if the 50 unsorted numbers are at the end of the array..then array would have to be shifted approx 50n times..and if 50<<<n..it can be neglected..hence linear time///
- Anonymous January 15, 2010