Find the Kth smallest element in the sorted generated array | Function to return the Kth element in B [ ] ; Initialize the count Array ; Reduce N repeatedly to half its value ; Add count to start ; Subtract same count after end index ; Store each element of Array [ ] with their count ; Sort the elements wrt value ; If Kth element is in range of element [ i ] return element [ i ] ; If K is out of bound ; Driver code
def solve ( Array , N , K ) : NEW_LINE INDENT count_Arr = [ 0 ] * ( N + 2 ) ; NEW_LINE factor = 1 ; NEW_LINE size = N ; NEW_LINE while ( size ) : NEW_LINE INDENT start = 1 ; NEW_LINE end = size ; NEW_LINE count_Arr [ 1 ] += factor * N ; NEW_LINE count_Arr [ end + 1 ] -= factor * N ; NEW_LINE factor += 1 ; NEW_LINE size //= 2 ; NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT count_Arr [ i ] += count_Arr [ i - 1 ] ; NEW_LINE DEDENT element = [ ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT element . append ( ( Array [ i ] , count_Arr [ i + 1 ] ) ) ; NEW_LINE DEDENT element . sort ( ) ; NEW_LINE start = 1 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT end = start + element [ i ] [ 1 ] - 1 ; NEW_LINE if ( K >= start and K <= end ) : NEW_LINE INDENT return element [ i ] [ 0 ] ; NEW_LINE DEDENT start += element [ i ] [ 1 ] ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 5 , 1 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 13 ; NEW_LINE print ( solve ( arr , N , K ) ) ; NEW_LINE DEDENT