Given an array of integer values which need to be sorted by only one operation – subarray rotation where subarray size should be 3. For example, If our array is (1 2 3 4) then we can reach to (1 4 2 3), (3 1 2 4) in one step. We need to tell whether it is possible to sort the complete array with this operation or not.
Input : arr = [1, 3, 4, 2] Output : Yes Possible by below rotations, [1, 3, 4, 2] -> [1, 4, 2, 3] -> [1, 2, 3, 4] Input : arr = [1, 2, 4, 3] Output : No Not possible to sort above array by any 3 size subarray rotation.
Suppose we have one subarray as [A[i] A[i+1] A[i+2]]. After one rotation, we get [A[i+2], A[i], A[i+1]]
If we observe inversions before and after rotation, we can see that parity of inversion is not changed i.e. if [A[i] A[i+1] A[i+2]] has even number of inversions [A[i+2] A[i] A[i+1]] will have even inversions. Same is true for odd inversions. Due to movement of A[i+2], inversions either increase by 2 or decrease by 2 or remain same i.e. their parity won’t change.
After observing above fact we can say that if initial array configuration has even number of inversion then it is possible to make them zero making array completely sorted otherwise not. We use merge sort based method for counting inversions. After getting the number of inversions, we can easily check parity of inversion and conclude whether it is possible to sort the array or not.
Time Complexity : O(n Log n)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum subarray size, such that all subarrays of that size have sum less than k
- Sorting array except elements in a subarray
- Subarray of size k with given sum
- Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
- Size of The Subarray With Maximum Sum
- Largest product of a subarray of size k
- Smallest subarray whose sum is multiple of array size
- Maximum Unique Element in every subarray of size K
- Find a subarray whose sum is divisible by size of the array
- Find maximum (or minimum) sum of a subarray of size k
- Maximum average of a subarray of size of atleast X and atmost Y
- Count number of permutation of an Array having no SubArray of size two or more from original Array
- Know Your Sorting Algorithm | Set 1 (Sorting Weapons used by Programming Languages)
- Know Your Sorting Algorithm | Set 2 (Introsort- C++’s Sorting Weapon)
- Maximize the subarray sum after multiplying all elements of any subarray with X