Sort given Array using at most N cyclic shift on any subarray
Given an array arr containing N integers, with duplicates. The task is to sort the array in increasing order using at most N cyclic shift on any sub-array.
Cyclic shift on any sub-array means cut out any subarray from the given array, use cyclic shift (rotate) in it by any offset, and put it back into the same place of the array.
Print the number of such shifting required to sort the array. There can be multiple possibilities.
Input: arr = [1, 3, 2, 8, 5]
Explanation: Consider segment from index = 1 to index = 2. [1, 3, 2, 8, 5]. Now rotate this segment by 1 offset. The new array becomes, [1, 2, 3, 8, 5].
Then consider segment from index = 3 to index = 4, [1, 2, 3, 8, 5]. Rotate it by 1 offset, the new array becomes, [1, 2, 3, 5, 8].
Input: arr = [2, 4, 1, 3]
Explanation: From index = 0 to index = 2, [2, 4, 1, 3]. Rotate this segment by 2 offset on left, the new array becomes, [1, 2, 4, 3].
Taking second segment from index = 2 to index = 3 of offset 1, rotate it the new array becomes, [1, 2, 4, 3].
Approach: There can be two cases:
- Case when the array is already sorted: Then we do not need to perform any shifting operation
- Case when the array is not sorted: For that follow the steps mentioned below:
- Create a variable count = 0 to store the total number of counts.
- Iterate from i = 0 to i = N-2. And for each iteration do the following operations:
- Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i].
- Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal.
- Mark that position right to perform cyclic shift from i to right by offset 1.
- If no such right value exists then simply move to the next iteration.
- Otherwise, rotate the array from i to right by 1 position and increment count by 1.
- Return the value of count as your answer.
Below is the C++ implementation for the above approach:
Time Complexity: O(N2)
Space Complexity: O(1)