This can be done by piggybacking on MergeSort Routine.
The real action takes places in the merge stage of the merge sort routine.
The idea here is for any index i
of the merged array
- If the element to be added has the same index as the index being inserted to then we know that it forms a group and we increment the group count by 1.
Suppose i/p = [1, 7, 5, 4, 2, 12]
We create a new array which stores the indices of the elements [0, 1, 2, 3, 4, 5, 6]
for the given input the first merge function will be called for
left SubArray => 0
right SubArray => 1
For the 0th element of the new merged array we look at the which element we can use.
so for 0th of the new element comes from index 0, i.e. 1, which are the same so we increment the number of groups by 1. Same for index 1
- Suppose for index i in the merged array the element from index j, where j > i has to be inserted, we for now know that the subarray from i to j could be a group if all the elements in the range [i, j] in the merged array falls with this range. In case we encounter another index to be added
k
which is greater that j
we will update the index we are looking for to include k i.e. [i, k]
. Because, if we consider only range [i, j]
we will have a element at k
where input[k] > input[j]
thereby not forming a valid group.
Example input = [3, 2, 0, 1]
which will become [0, 1, 2, 3]
for the last merge
the left subarray will be
[1, 0]
the right subarray will be
[2, 3 ]`
for index 0 of the merged array we look at minimum of input[1]
or input[2]
which is input[2] and the index is 2, so we now know that the minimum this array comes from index 2. We continue to look until the index 3 in the merged array and updating the highest index the which contributes a group and stop when both the indices become the same
at index 1, we have choose between index 1, 3 and we find out index [3] is the next least minimum and we update the highest index to 3 and continue until index i
of the merged index becomes equal to the index of the element being inserted.
It runs in O(N log N)
and we get result of the indices array is the sorted indices of the input
array