Given a binary array, task is to sort this binary array using minimum swaps. We are allowed to swap only adjacent elements
Input : [0, 0, 1, 0, 1, 0, 1, 1] Output : 3 1st swap : [0, 0, 1, 0, 0, 1, 1, 1] 2nd swap : [0, 0, 0, 1, 0, 1, 1, 1] 3rd swap : [0, 0, 0, 0, 1, 1, 1, 1] Input : Array = [0, 1, 0, 1, 0] Output : 3
This can be done by finding number of zeroes to the right side of every 1 and add them. In order to sort the array every one always has to perform a swap operation with every zero on its right side. So the total number of swap operations for a particular 1 in array is the number of zeroes on its right hand side. Find the number of zeroes on right side for every one i.e. the number of swaps and add them all to obtain the total number of swaps.
Time Complexity : O(n)
Auxiliary Space : O(n)
- Minimum number of swaps required to sort an array
- Minimum number of swaps required to sort an array | Set 2
- Minimum number of swaps required for arranging pairs adjacent to each other
- Minimum swaps required to convert one binary string to another
- Minimum swaps required to make a binary string divisible by 2^k
- Minimum swaps required to make a binary string alternating
- Minimum operations required to modify the array such that parity of adjacent elements is different
- Number of swaps to sort when only adjacent swapping allowed
- Minimum swaps to reach permuted array with at most 2 positions left swaps allowed
- Minimum Swaps required to group all 1's together
- Minimum number of adjacent swaps for arranging similar elements together
- Minimum swaps required to bring all elements less than or equal to k together
- Minimum inversions required so that no two adjacent elements are same
- Minimum swaps so that binary search can be applied
- Minimum number of swaps to make two binary string equal
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.