Given an array arr[] of N integers and an integer K, the task is to find the minimum number of operations required to sort the array in non-decreasing order such that in each operation any array element arr[i] can be swapped with K if the value of (arr[i] > K).
Examples:
Input: arr[] = {0, 2, 3, 5, 4}, K = 1
Output: 3Â
Explanation:
The given array can be sorted using the following steps:
- For i = 1, since arr[1] > K, swapping the values of arr[1] and K. Hence, the array becomes {0, 1, 3, 5, 4} and value of K = 2.
- For i = 2, since arr[2] > K, swapping the values of arr[2] and K. Hence, the array becomes {0, 1, 2, 5, 4} and value of K = 3.
- For i = 3, since arr[3] > K, swapping the values of arr[3] and K. Hence, the array becomes {0, 1, 2, 3, 4} and value of K = 5.
After the above operations, the given array has been sorted.
ÂInput: arr[] = {1, 3, 5, 9, 7}, K = 10
Output: -1Â
Approach: The given problem can be solved using a Greedy Approach, the idea is to minimize the value of arr[i] at each step for all i in the range [0, N – 1] which is the most optimal choice for the further array to be sorted. Therefore, if the value of arr[i] > K, swapping the values of arr[i] and K is the most optimal choice. Follow the steps below to solve the given problem:
- Create a variable cnt, which stores the count of the operations performed. Initially cnt = 0.
- Traverse the array arr[] using a variable i in the range [0, N-1] in increasing order of i.
- For each index, if arr[i] > K, swap the value of K and arr[i] and increment the value of cnt by 1.
- After every operation, check whether the array arr[] is sorted or not using the approach discussed in this article. If the array arr[] is sorted, return the value of cnt as the required answer.
- If the array is not sorted after performing the above steps, the print -1.
Below is the implementation of the above approach:
C++
// C++ program of the above approach Â
#include <bits/stdc++.h> using namespace std; Â
// Function to find the minimum number // of given operations in order to sort // the array arr[] in non-decreasing order int minimumswaps( int arr[], int N, int K) { Â Â Â Â // If arr[] is already sorted, return 0 Â Â Â Â if (is_sorted(arr, arr + N)) { Â Â Â Â Â Â Â Â return 0; Â Â Â Â } Â
    // Stores the count of operations     int cnt = 0; Â
    // Loop to iterate over the array     for ( int i = 0; i < N; i++) { Â
        // If arr[i] is greater than K,         // minimize the value of arr[i]         if (arr[i] > K) {             swap(arr[i], K); Â
            // Increment the count by 1             cnt++; Â
            // Check if the array is sorted             // after the last operation             if (is_sorted(arr, arr + N)) { Â
                // Return answer                 return cnt;             }         }     } Â
    // Not Possible to sort the array using     // given operation, hence return -1     return -1; } Â
// Driver Code int main() { Â Â Â Â int arr[] = { 0, 2, 3, 5, 4 }; Â Â Â Â int N = sizeof (arr) / sizeof (arr[0]); Â Â Â Â int K = 1; Â
    cout << minimumswaps(arr, N, K); Â
    return 0; } |
Java
// Java program of the above approach import java.io.*; class GFG { Â Â Â Â static boolean is_sorted( int arr[], int N) Â Â Â Â { Â Â Â Â Â Â Â Â for ( int i = 0 ; i < N - 1 ; i++) Â Â Â Â Â Â Â Â { Â
            if (arr[i] > arr[i + 1 ])                 return false ;         } Â
        return true ;     } Â
    // Function to find the minimum number     // of given operations in order to sort     // the array arr[] in non-decreasing order     static int minimumswaps( int arr[], int N, int K)     {                // If arr[] is already sorted, return 0         if (is_sorted(arr, N)) {             return 0 ;         } Â
        // Stores the count of operations         int cnt = 0 ; Â
        // Loop to iterate over the array         for ( int i = 0 ; i < N; i++) { Â
            // If arr[i] is greater than K,             // minimize the value of arr[i]             if (arr[i] > K) {                 int temp = arr[i];                   arr[i] = K;                   K = temp; Â
                // Increment the count by 1                 cnt++; Â
                // Check if the array is sorted                 // after the last operation                 if (is_sorted(arr, N)) { Â
                    // Return answer                     return cnt;                 }             }         } Â
        // Not Possible to sort the array using         // given operation, hence return -1         return - 1 ;     } Â
    // Driver Code     public static void main(String[] args)     {         int arr[] = { 0 , 2 , 3 , 5 , 4 };         int N = arr.length;            int K = 1 ; Â
        System.out.println(minimumswaps(arr, N, K));     } } Â
// This code is contributed by Dharanendra L V. |
Python3
# Python 3 program of the above approach def is_sort(arr):     for i in range ( len (arr) - 1 ):         if arr[i]>arr[i + 1 ]:             return False     return True    # Function to find the minimum number # of given operations in order to sort # the array arr[] in non-decreasing order def minimumswaps(arr, N, K):        # If arr[] is already sorted, return 0     if is_sort(arr):         return 0 Â
    # Stores the count of operations     cnt = 0 Â
    # Loop to iterate over the array     for i in range (N):         # If arr[i] is greater than K,         # minimize the value of arr[i]         if (arr[i] > K):             temp = arr[i]             arr[i] = K             K = temp                          # Increment the count by 1             cnt + = 1 Â
            # Check if the array is sorted             # after the last operation             if is_sort(arr):                 # Return answer                 return cnt Â
    # Not Possible to sort the array using     # given operation, hence return -1     return - 1 Â
# Driver Code if __name__ = = '__main__' : Â Â Â Â arr = [ 0 , 2 , 3 , 5 , 4 ] Â Â Â Â N = len (arr) Â Â Â Â K = 1 Â Â Â Â print (minimumswaps(arr, N, K)) Â Â Â Â Â Â Â Â Â # This code is contributed by bgangwar59. |
C#
// C# program of the above approach using System; class GFG { Â Â Â Â static bool is_sorted( int [] arr, int N) Â Â Â Â { Â Â Â Â Â Â Â Â for ( int i = 0; i < N - 1; i++) { Â
            if (arr[i] > arr[i + 1])                 return false ;         } Â
        return true ;     } Â
    // Function to find the minimum number     // of given operations in order to sort     // the array arr[] in non-decreasing order     static int minimumswaps( int [] arr, int N, int K)     { Â
        // If arr[] is already sorted, return 0         if (is_sorted(arr, N)) {             return 0;         } Â
        // Stores the count of operations         int cnt = 0; Â
        // Loop to iterate over the array         for ( int i = 0; i < N; i++) { Â
            // If arr[i] is greater than K,             // minimize the value of arr[i]             if (arr[i] > K) {                 int temp = arr[i];                 arr[i] = K;                 K = temp; Â
                // Increment the count by 1                 cnt++; Â
                // Check if the array is sorted                 // after the last operation                 if (is_sorted(arr, N)) { Â
                    // Return answer                     return cnt;                 }             }         } Â
        // Not Possible to sort the array using         // given operation, hence return -1         return -1;     } Â
    // Driver Code     public static void Main( string [] args)     {         int [] arr = { 0, 2, 3, 5, 4 };         int N = arr.Length;         int K = 1; Â
        Console.WriteLine(minimumswaps(arr, N, K));     } } Â
// This code is contributed by ukasp. |
Javascript
<script>         // JavaScript Program to implement         // the above approach         function is_sorted(arr, N) {             for (let i = 0; i < N - 1; i++) { Â
                if (arr[i] > arr[i + 1])                     return false ;             } Â
            return true ;         } Â
        // Function to find the minimum number         // of given operations in order to sort         // the array arr[] in non-decreasing order         function minimumswaps(arr, N, K)         {                      // If arr[] is already sorted, return 0             if (is_sorted(arr, N)) {                 return 0;             } Â
            // Stores the count of operations             let cnt = 0; Â
            // Loop to iterate over the array             for (let i = 0; i < N; i++) { Â
                // If arr[i] is greater than K,                 // minimize the value of arr[i]                 if (arr[i] > K) {                     let temp = arr[i];                     arr[i] = K;                     K = temp; Â
                    // Increment the count by 1                     cnt++; Â
                    // Check if the array is sorted                     // after the last operation                     if (is_sorted(arr, N)) { Â
                        // Return answer                         return cnt;                     }                 }             } Â
            // Not Possible to sort the array using             // given operation, hence return -1             return -1;         } Â
        // Driver Code         let arr = [0, 2, 3, 5, 4];         let N = arr.length;         let K = 1; Â
        document.write(minimumswaps(arr, N, K)); Â
     // This code is contributed by Potta Lokesh Â
    </script> |
3
Â
Time Complexity: O(N2)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!