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 ; First odd number ; Insert the odd number ; Next odd number ; First even number ; Insert the even number ; Next even number ; Return the kth element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getNumber ( int n , int k ) { int arr [ n ] ; int i = 0 ; int odd = 1 ; while ( odd <= n ) { arr [ i ++ ] = odd ; odd += 2 ; } int even = 2 ; while ( even <= n ) { arr [ i ++ ] = even ; even += 2 ; } return arr [ k - 1 ] ; } int main ( ) { int n = 8 , k = 5 ; cout << getNumber ( n , k ) ; return 0 ; }