Find Kth element in an array containing odd elements first and then even elements | C ++ implementation of the approach ; Function to return the kth element in the modified array ; Finding the index from where the even numbers will be stored ; Return the kth element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getNumber ( int n , int k ) { int pos ; if ( n % 2 == 0 ) { pos = n / 2 ; } else { pos = ( n / 2 ) + 1 ; } if ( k <= pos ) { return ( k * 2 - 1 ) ; } else return ( ( k - pos ) * 2 ) ; } int main ( ) { int n = 8 , k = 5 ; cout << getNumber ( n , k ) ; return 0 ; }