I want to reverse an array (or any other data structure) but because this operation is going to be done on the array for n times , im looking for the best solution possible, I have the sorted array , which is gotten in O(nlgn) time , i start looking for first element in the sorted array , inside the unsorted array ( which is equal to finding the smallest key in the unsorted array ) then I reverse the array from the beginning to the index of that value , then i do the same for the rest , find the second smallest value’s index , and reverse the array again , from the second index to the end of the array and so on :
for example , consider this array :
*2 6 (*1*) 5 4 *3 // array is reversed from its 0th index to the 3rd index (0 based)
1 *5* 4 3 6 (*2*) // array is reversed from its 1st index (0 based ) to the 5th index
1 2 *6* *3* 4 5 // and ...
1 2 3 *6* *4* 5
1 2 3 4 *6* *5*
1 2 3 4 5 6
well i have to sort the array in order to have the values im looking for in the unsorted array , it’ll take o(nlgn) time , and doing the algorithm above , will take o(n^2) ,any idea to make it more quick , to be done in o(nlgn) time ? so the question is reversing a sub array of the array in the least time Order , cause it’s done for many times in large sized arrays. ( I can get the indices i and j ( which are the first and last index of the sub array ) in O (n) time cause i have the sorted array and i’ll just look up the numbers in the unsorted array ) so im looking for the best time order for reversing an array from it’s ith index to it’s jth index .
thanks in advance
Here comes an O(
n) solution (i think, reading your description was hard). It’s a data structure wich allows 1) reversing a sub-array in O(1), 2) Getting a value from the array in O(r), whereris the number of reversings that is done, 3) find the index of an element in O(n), wherenis the length of the list.Just store our array as usual, and have a list of
ReversedRange(imin, imax)elements. Reversing part of the array is as easy as inserting another element in this list.Whenever you need to get a value from the modified array at index
i, you look through all theReversedRangefor whichimin <= i <= imax, and calculate the indexjwhich corresponds to the original array index. You need to checkrreversings, so it is O(r).To get the index
iof a valuev, look through the original array and find the indexj. Done in O(n) time. Do the same traversing of theReversedRanges, only in the oppsite direction to calculatei. Done in O(r) time, total O(n+r) which is O(n).Example
Consider the following list:
0 1 2 3 4 5 6 7 8 9. Now say we reverse the list form indexes1through6, and then from0through5. So we have:No let us map the index
i = 2to the original array. From the graph we see that we should end up withIII(2) = 4