Position of an element after stable sort | C ++ program to get index of array element in sorted array ; Method returns the position of arr [ idx ] after performing stable - sort on array ; Count of elements smaller than current element plus the equal element occurring before given index ; If element is smaller then increase the smaller count ; If element is equal then increase count only if it occurs before ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getIndexInSortedArray ( int arr [ ] , int n , int idx ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ idx ] ) result ++ ; if ( arr [ i ] == arr [ idx ] && i < idx ) result ++ ; } return result ; } int main ( ) { int arr [ ] = { 3 , 4 , 3 , 5 , 2 , 3 , 4 , 3 , 1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int idxOfEle = 5 ; cout << getIndexInSortedArray ( arr , n , idxOfEle ) ; return 0 ; }