Minimize swaps required to maximize the count of elements replacing a greater element in an Array | Java Program to implement the above approach ; Function to find the minimum number of swaps required ; Sort the array in ascending order ; Iterate until a greater element is found ; Keep incrementing ind ; If a greater element is found ; Increase count of swap ; Increment ind ; If end of array is reached ; Return the answer ; Driver Code
import java . util . * ; class GFG { static int countSwaps ( int A [ ] , int n ) { Arrays . sort ( A ) ; int ind = 1 , res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( ind < n && A [ ind ] == A [ i ] ) ind ++ ; if ( ind < n && A [ ind ] > A [ i ] ) { res ++ ; ind ++ ; } if ( ind >= n ) break ; } return res ; } public static void main ( String [ ] args ) { int A [ ] = { 4 , 3 , 3 , 2 , 5 } ; System . out . print ( countSwaps ( A , 5 ) ) ; } }