Minimize swaps required to place largest and smallest array elements at first and last array indices | C ++ program for the above approach ; Function to find the minimum count of adjacent swaps to move largest and smallest element at the first and the last index of the array , respectively ; Stores the smallest array element ; Stores the smallest array element ; Stores the last occurrence of the smallest array element ; Stores the first occurrence of the largest array element ; Traverse the array arr [ ] ; If a [ i ] is less than min_element ; Update min_element ; Update min_ind ; If a [ i ] is greater than max_element ; Update max_element ; Update max_ind ; If max_ind is equal to min_ind ; Return 0 ; If max_ind is greater than min_ind ; Otherwise ; Driver Code ; Input ; Print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMoves ( int * a , int n ) { int min_element = INT_MAX ; int max_element = INT_MIN ; int min_ind = -1 ; int max_ind = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] <= min_element ) { min_element = a [ i ] ; min_ind = i ; } if ( a [ i ] > max_element ) { max_element = a [ i ] ; max_ind = i ; } } if ( max_ind == min_ind ) { return 0 ; } else if ( max_ind > min_ind ) { return max_ind + ( n - min_ind - 2 ) ; } else { return max_ind + n - min_ind - 1 ; } } int main ( ) { int arr [ ] = { 35 , 46 , 17 , 23 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumMoves ( arr , N ) << endl ; }