📌  相关文章
📜  排序二进制数组所需的最小相邻交换

📅  最后修改于: 2021-05-06 17:59:05             🧑  作者: Mango

给定一个二进制数组,任务是使用最少交换对该二进制数组进行排序。我们只允许交换相邻的元素

例子:

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
推荐:请首先在IDE上尝试您的方法,然后查看解决方案

方法 :
这可以通过在每个1的右侧找到零的数目并将其相加来完成。为了对数组进行排序,每个人总是必须在其右边的每个零处执行交换操作。因此,数组中特定1的交换操作总数为其右侧的零个数。找出每一个右边的零数,即掉期数,并将它们全部相加以获得掉期总数。

执行 :

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[0]);
    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
?>


Javascript


C++
// this code is contributed by Manu Pathria
#include 
using namespace std;
 
int minswaps(int arr[], int n)
{
    int count = 0;
    int num_unplaced_zeros = 0;
      
    for(int index=n-1;index>=0;index--)
    {
        if(arr[index] == 0)
            num_unplaced_zeros += 1;
        else
            count += num_unplaced_zeros;
    }
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = {0, 0, 1, 0, 1, 0, 1, 1};
    cout<


Java
import java.io.*;
 
class GFG {
    public static int minswaps(int arr[], int n)
    {
        int count = 0;
        int num_unplaced_zeros = 0;
 
        for (int index = n - 1; index >= 0; index--)
        {
            if (arr[index] == 0)
                num_unplaced_zeros += 1;
            else
                count += num_unplaced_zeros;
        }
        return count;
    }
   
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 0, 0, 1, 0, 1, 0, 1, 1 };
        System.out.println(minswaps(arr, 9));
    }
}
 
// this code is contributed by Manu Pathria


Python3
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, 0, 1, 1]
print(minswaps(arr))


输出
3

时间复杂度: O(n)
辅助空间: O(n)

空间优化解决方案:
不需要辅助空间。我们只需要从背面开始阅读列表,并跟踪遇到的零的数量。如果我们遇到1,则零数是将1放置在正确位置所需的掉期数。

C++

// this code is contributed by Manu Pathria
#include 
using namespace std;
 
int minswaps(int arr[], int n)
{
    int count = 0;
    int num_unplaced_zeros = 0;
      
    for(int index=n-1;index>=0;index--)
    {
        if(arr[index] == 0)
            num_unplaced_zeros += 1;
        else
            count += num_unplaced_zeros;
    }
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = {0, 0, 1, 0, 1, 0, 1, 1};
    cout<

Java

import java.io.*;
 
class GFG {
    public static int minswaps(int arr[], int n)
    {
        int count = 0;
        int num_unplaced_zeros = 0;
 
        for (int index = n - 1; index >= 0; index--)
        {
            if (arr[index] == 0)
                num_unplaced_zeros += 1;
            else
                count += num_unplaced_zeros;
        }
        return count;
    }
   
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 0, 0, 1, 0, 1, 0, 1, 1 };
        System.out.println(minswaps(arr, 9));
    }
}
 
// this code is contributed by Manu Pathria

Python3

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, 0, 1, 1]
print(minswaps(arr))
输出
3

时间复杂度: O(n)
辅助空间: O(1)