📌  相关文章
📜  通过与 X 交换对 Array 进行排序所需的最小移动次数

📅  最后修改于: 2021-10-26 02:33:17             🧑  作者: Mango

给定一个整数数组,大小为N 的arr[]和一个整数X 。任务是通过将任何大于X 的数组元素与X任意次数交换,以最少的移动次数按递增顺序对数组进行排序。如果不可能打印-1

例子:

方法:可以使用贪心方法解决给定的问题。请按照以下步骤解决问题:

  • 将变量ans初始化为 0 以存储所需的结果。
  • 使用变量i遍历[0, N-1]范围内的数组arr[]
    • 如果arr[i]>arr[i+1]的值,则使用变量j在范围[0, i] 中迭代并将arr[j]X交换,如果arr[j]>X 的值,则将ans的值增加 1。
  • 检查数组是否已排序。如果不是,则将ans更新为 -1。
  • 打印ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the minimum number of
// moves required to sort the array
void minSwaps(int a[], int n, int x)
{
    int c = 0;
 
    // Store the required number of moves
    int ans = 0;
 
    // Traverse the array, arr[]
    for (int i = 0; i < n - 1; i++) {
 
        // If mismatch found
        if (a[i] > a[i + 1]) {
 
            // Start from first index to
            // maintain the increasing order
            // of array
            for (int k = 0; k <= i; k++) {
 
                // If true, swap a[k] and x
                // and increment ans by 1
                if (a[k] > x) {
                    int tt = a[k];
                    a[k] = x;
                    x = tt;
                    ans++;
                }
            }
        }
    }
 
    // Check if now the array is sorted,
    // if not, set c=1
    for (int i = 0; i < n - 1; i++) {
        if (a[i] > a[i + 1]) {
            c = 1;
            break;
        }
    }
 
    // Print the result
    if (c == 1) {
        cout << "-1";
    }
    else {
        cout << ans;
    }
}
 
// Driver Code
int main()
{
    // Given Input
    int n = 5;
    int x = 2;
    int a[] = { 1, 3, 4, 6, 5 };
 
    // Function Call
    minSwaps(a, n, x);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG
{
 
  // Function to find the minimum number of
  // moves required to sort the array
  static void minSwaps(int a[], int n, int x)
  {
    int c = 0;
 
    // Store the required number of moves
    int ans = 0;
 
    // Traverse the array, arr[]
    for (int i = 0; i < n - 1; i++) {
 
      // If mismatch found
      if (a[i] > a[i + 1]) {
 
        // Start from first index to
        // maintain the increasing order
        // of array
        for (int k = 0; k <= i; k++) {
 
          // If true, swap a[k] and x
          // and increment ans by 1
          if (a[k] > x) {
            int tt = a[k];
            a[k] = x;
            x = tt;
            ans++;
          }
        }
      }
    }
 
    // Check if now the array is sorted,
    // if not, set c=1
    for (int i = 0; i < n - 1; i++) {
      if (a[i] > a[i + 1]) {
        c = 1;
        break;
      }
    }
 
    // Print the result
    if (c == 1) {
      System.out.println("-1");
    }
    else {
      System.out.println(ans);
    }
  }
 
  // Driver Code
  public static void main (String[] args)
  {
 
    // Given Input
    int n = 5;
    int x = 2;
    int a[] = { 1, 3, 4, 6, 5 };
 
    // Function Call
    minSwaps(a, n, x);
  }
}
 
// This code is contributed by Potta Lokesh


Python3
# Python3 program for the above approach
 
# Function to find the minimum number of
# moves required to sort the array
def minSwaps(a, n, x):
     
    c = 0
 
    # Store the required number of moves
    ans = 0
 
    # Traverse the array, arr[]
    for i in range(n - 1):
         
        # If mismatch found
        if (a[i] > a[i + 1]):
 
            # Start from first index to
            # maintain the increasing order
            # of array
            for k in range(i + 1):
                 
                # If true, swap a[k] and x
                # and increment ans by 1
                if (a[k] > x):
                    tt = a[k]
                    a[k] = x
                    x = tt
                    ans += 1
 
    # Check if now the array is sorted,
    # if not, set c=1
    for i in range(n - 1):
        if (a[i] > a[i + 1]):
            c = 1
            break
 
    # Print the result
    if (c == 1):
        print("-1")
    else:
        print(ans)
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    n = 5
    x = 2
    a = [ 1, 3, 4, 6, 5 ]
 
    # Function Call
    minSwaps(a, n, x)
 
# This code is contributed by ipg2016107


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the minimum number of
// moves required to sort the array
static void minSwaps(int[] a, int n, int x)
{
    int c = 0;
     
    // Store the required number of moves
    int ans = 0;
     
    // Traverse the array, arr[]
    for(int i = 0; i < n - 1; i++)
    {
     
        // If mismatch found
        if (a[i] > a[i + 1])
        {
         
            // Start from first index to
            // maintain the increasing order
            // of array
            for(int k = 0; k <= i; k++)
            {
             
                // If true, swap a[k] and x
                // and increment ans by 1
                if (a[k] > x)
                {
                    int tt = a[k];
                    a[k] = x;
                    x = tt;
                    ans++;
                }
            }
        }
    }
     
    // Check if now the array is sorted,
    // if not, set c=1
    for(int i = 0; i < n - 1; i++)
    {
        if (a[i] > a[i + 1])
        {
            c = 1;
            break;
        }
    }
 
    // Print the result
    if (c == 1)
    {
        Console.Write("-1");
    }
    else
    {
        Console.Write(ans);
    }
}
 
// Driver Code
static public void Main()
{
     
    // Given Input
    int n = 5;
    int x = 2;
    int[] a = { 1, 3, 4, 6, 5 };
  
    // Function Call
    minSwaps(a, n, x);
}
}
 
// This code is contributed by avijitmondal1998


Javascript


输出
3

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程