## Microsoft Interview Question

Dev Leads**Country:**United States

For nearly sorted data insertion sort will be best. Let maximum displaced elements are k distance away. For ex. (3 2 1 4 6 5) k = 3. Then insertion sort will be O(kN).

If elements are nearly sorted like (3 4 5 2 1) few elements are n distance away and rest are sorted. Then also insertion sort will be O(kN)

Well, the way you wrote the example, I would wonder if the interview is actually asking about a rotated, linear data structure (e.g. rotated array or DLL).

If the answer is yes, then I would apply a binary search to identify the point of rotation (a situation in which the left element is greater than the adjacent, right element). Once the split point is a found, a series of shifts would occur for an array, or a single pointer adjustment for a DLL, in order to change to a sorted list.

O(lgn) to find + O(1) for a DLL

or

O(lgn) + O(n) for an array

This would be better than any comparison-based sorting.

in case of given example the best is insertion sort (14 iterations) against ShellSort (21 iterations), bubble sort (28 iterations) and selection sort (28 iterations).

I'm thinking insertion sort for the first case.

- Lucas Pantalones January 24, 2016For the second case, if it is mostly unsorted, then a standard mergesort or quicksort should do the job. If it is still mostly sorted (just not the extreme case given), then mergesort would probably be safest. In both of these second cases, radix sort could be best depending on the domain.