I am actually trying to solve a problem where I have an array which is sorted but a few numbers are reversed . For example : 1 2 3 4 9 8 7 11 12 14 is the array.
Now , my first thought was applying a Binary Search algorithm to find a PEAK ( a[i]>a[i+1] && a[i]>a[i-1])
However , I feel it might not always give the correct result. Moreover it might not be efficient since the list is almost sorted.
Next impression : Applying Insertion Sort since the list is sorted and insertion sort gives best performance in such case IF I am not wrong.
So can anyone suggest better solutions or whether my solutions are correct or not? Efficient of In-efficient?
P.S – This is NOT homework !
UPDATE : Insertion Sort (O(n) in this case) or Linear Scan to find the subsequence and then reversing it (O(n)) again. Is there any chance if we could optimize it? Or probably do in O(logn) ?
Search linearly for the first inversion (i.e.
a[i+1] < a[i]), call its indexinv1. Continue until inversions stop, call the last indexinv2. Reverse the array betweeninv1andinv2, inclusive.In your example,
inv1is 4, andinv2is 6; array elements are numbered from zero.The algorithm is linear in the number of entries in the original.