Convert an array to reduced form | Set 3 ( Binary Search ) | C ++ program for the above approach ; Function to find the reduced form of the given array arr [ ] ; Stores the sorted form of the the given array arr [ ] ; Sort the array brr [ ] ; Traverse the given array arr [ ] ; Perform the Binary Search ; Calculate the value of mid ; Print the current index and break ; Update the value of l ; Update the value of r ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void convert ( int arr [ ] , int n ) { int brr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) brr [ i ] = arr [ i ] ; sort ( brr , brr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { int l = 0 , r = n - 1 , mid ; while ( l <= r ) { mid = ( l + r ) / 2 ; if ( brr [ mid ] == arr [ i ] ) { cout << mid << ' ▁ ' ; break ; } else if ( brr [ mid ] < arr [ i ] ) { l = mid + 1 ; } else { r = mid - 1 ; } } } } int main ( ) { int arr [ ] = { 10 , 20 , 15 , 12 , 11 , 50 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; convert ( arr , N ) ; return 0 ; }