Find Kth element in an array containing odd elements first and then even elements | Java 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
class GFG { static int getNumber ( int n , int k ) { int [ ] arr = new int [ 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 ] ; } public static void main ( String [ ] args ) { int n = 8 , k = 5 ; System . out . println ( getNumber ( n , k ) ) ; } }