# Minimum adjacent swaps required to Sort Binary array

Given a binary array, task is to sort this binary array using minimum swaps. We are allowed to swap only adjacent elements

Examples:

```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
```

Approach :
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.

Implementation :

## C++

 `// C++ code to find minimum number of ` `// swaps to sort a binary array ` `#include ` ` `  `using` `namespace` `std; ` ` `  `// Function to find minimum swaps to ` `// sort an array of 0s and 1s. ` `int` `findMinSwaps(``int` `arr[], ``int` `n) ` `{ ` `    ``// Array to store count of zeroes ` `    ``int` `noOfZeroes[n]; ` `    ``memset``(noOfZeroes, 0, ``sizeof``(noOfZeroes)); ` ` `  `    ``int` `i, count = 0; ` ` `  `    ``// Count number of zeroes ` `    ``// on right side of every one. ` `    ``noOfZeroes[n - 1] = 1 - arr[n - 1]; ` `    ``for` `(i = n - 2; i >= 0; i--) { ` `        ``noOfZeroes[i] = noOfZeroes[i + 1]; ` `        ``if` `(arr[i] == 0) ` `            ``noOfZeroes[i]++; ` `    ``} ` ` `  `    ``// Count total number of swaps by adding number ` `    ``// of zeroes on right side of every one. ` `    ``for` `(i = 0; i < n; i++) { ` `        ``if` `(arr[i] == 1) ` `            ``count += noOfZeroes[i]; ` `    ``} ` ` `  `    ``return` `count; ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``int` `arr[] = { 0, 0, 1, 0, 1, 0, 1, 1 }; ` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr); ` `    ``cout << findMinSwaps(arr, n); ` `    ``return` `0; ` `} `

## Java

 `// Java code to find minimum number of ` `// swaps to sort a binary array ` `class` `gfg { ` `     `  `    ``static` `int` `findMinSwaps(``int` `arr[], ``int` `n) ` `    ``{ ` `        ``// Array to store count of zeroes ` `        ``int` `noOfZeroes[] = ``new` `int``[n]; ` `        ``int` `i, count = ``0``; ` ` `  `        ``// Count number of zeroes ` `        ``// on right side of every one. ` `        ``noOfZeroes[n - ``1``] = ``1` `- arr[n - ``1``]; ` `        ``for` `(i = n - ``2``; i >= ``0``; i--)  ` `        ``{ ` `            ``noOfZeroes[i] = noOfZeroes[i + ``1``]; ` `            ``if` `(arr[i] == ``0``) ` `                ``noOfZeroes[i]++; ` `        ``} ` ` `  `        ``// Count total number of swaps by adding number ` `        ``// of zeroes on right side of every one. ` `        ``for` `(i = ``0``; i < n; i++)  ` `        ``{ ` `            ``if` `(arr[i] == ``1``) ` `                ``count += noOfZeroes[i]; ` `        ``} ` `        ``return` `count; ` `    ``} ` `     `  `    ``// Driver Code ` `    ``public` `static` `void` `main(String args[]) ` `    ``{ ` `        ``int` `ar[] = { ``0``, ``0``, ``1``, ``0``, ``1``, ``0``, ``1``, ``1` `}; ` `        ``System.out.println(findMinSwaps(ar, ar.length)); ` `    ``} ` `} ` ` `  `// This code is contributed by Niraj_Pandey. `

## Python3

 `# Python3 code to find minimum number of ` `# swaps to sort a binary array ` ` `  `# Function to find minimum swaps to ` `# sort an array of 0s and 1s. ` `def` `findMinSwaps(arr, n) : ` `    ``# Array to store count of zeroes ` `    ``noOfZeroes ``=` `[``0``] ``*` `n ` `    ``count ``=` `0` `     `  `    ``# Count number of zeroes ` `    ``# on right side of every one. ` `    ``noOfZeroes[n ``-` `1``] ``=` `1` `-` `arr[n ``-` `1``] ` `    ``for` `i ``in` `range``(n``-``2``, ``-``1``, ``-``1``) : ` `        ``noOfZeroes[i] ``=` `noOfZeroes[i ``+` `1``] ` `        ``if` `(arr[i] ``=``=` `0``) : ` `            ``noOfZeroes[i] ``=` `noOfZeroes[i] ``+` `1` ` `  `    ``# Count total number of swaps by adding  ` `    ``# number of zeroes on right side of  ` `    ``# every one. ` `    ``for` `i ``in` `range``(``0``, n) : ` `        ``if` `(arr[i] ``=``=` `1``) : ` `            ``count ``=` `count ``+` `noOfZeroes[i] ` ` `  `    ``return` `count ` ` `  `# Driver code ` `arr ``=` `[ ``0``, ``0``, ``1``, ``0``, ``1``, ``0``, ``1``, ``1` `] ` `n ``=` `len``(arr) ` `print` `(findMinSwaps(arr, n)) ` ` `  `# This code is contributed by Manish Shaw ` `# (manishshaw1) `

## C#

 `// C# code to find minimum number of ` `// swaps to sort a binary array ` `using` `System; ` ` `  `class` `GFG { ` `     `  `    ``static` `int` `findMinSwaps(``int` `[]arr, ``int` `n) ` `    ``{ ` `         `  `        ``// Array to store count of zeroes ` `        ``int` `[]noOfZeroes = ``new` `int``[n]; ` `        ``int` `i, count = 0; ` ` `  `        ``// Count number of zeroes ` `        ``// on right side of every one. ` `        ``noOfZeroes[n - 1] = 1 - arr[n - 1]; ` `        ``for` `(i = n - 2; i >= 0; i--)  ` `        ``{ ` `            ``noOfZeroes[i] = noOfZeroes[i + 1]; ` `            ``if` `(arr[i] == 0) ` `                ``noOfZeroes[i]++; ` `        ``} ` ` `  `        ``// Count total number of swaps by  ` `        ``// adding number of zeroes on right ` `        ``// side of every one. ` `        ``for` `(i = 0; i < n; i++)  ` `        ``{ ` `            ``if` `(arr[i] == 1) ` `                ``count += noOfZeroes[i]; ` `        ``} ` `         `  `        ``return` `count; ` `    ``} ` `     `  `    ``// Driver Code ` `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``int` `[]ar = { 0, 0, 1, 0, 1, ` `                                ``0, 1, 1 }; ` `                                 `  `        ``Console.WriteLine( ` `              ``findMinSwaps(ar, ar.Length)); ` `    ``} ` `} ` ` `  `// This code is contributed by vt_m. `

## PHP

 `= 0; ``\$i``--) ` `    ``{ ` `        ``\$noOfZeroes``[``\$i``] = ``\$noOfZeroes``[``\$i` `+ 1]; ` `        ``if` `(``\$arr``[``\$i``] == 0) ` `            ``\$noOfZeroes``[``\$i``]++; ` `    ``} ` ` `  `    ``// Count total number of swaps by adding  ` `    ``// number of zeroes on right side of every one. ` `    ``for` `(``\$i` `= 0; ``\$i` `< ``\$n``; ``\$i``++)  ` `    ``{ ` `        ``if` `(``\$arr``[``\$i``] == 1) ` `            ``\$count` `+= ``\$noOfZeroes``[``\$i``]; ` `    ``} ` ` `  `    ``return` `\$count``; ` `} ` ` `  `// Driver code ` `\$arr` `= ``array``( 0, 0, 1, 0, 1, 0, 1, 1 ); ` `\$n` `= sizeof(``\$arr``); ` `echo` `findMinSwaps(``\$arr``, ``\$n``); ` ` `  `// This code is contributed by Sach_code ` `?> `

Output :

`3`

Time Complexity : O(n)
Auxiliary Space : O(n)

Space Optimized Solution :
An auxiliary space is not needed. We just need to start reading the list from the back and keep track of number of zeros we encounter. If we encounter a 1 the number of zeros is the number of swaps needed to put the 1 in correct place.

 `def` `minswaps(arr): ` `    ``count ``=` `0` `    ``num_unplaced_zeros ``=` `0` `      `  `    ``for` `index ``in` `range``(``len``(arr)``-``1``,``-``1``,``-``1``): ` `        ``if` `arr[index] ``=``=` `0``: ` `            ``num_unplaced_zeros ``+``=` `1` `        ``else``: ` `            ``count ``+``=` `num_unplaced_zeros ` `    ``return` `count ` `  `  `arr ``=` `[``0``, ``0``, ``1``, ``0``, ``1``, ``1``, ``0``, ``1``, ``1``]  ` `print``(minswaps(arr)) `

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.

Article Tags :
Practice Tags :

2

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.