Sort an Array which contain 1 to N values in O ( N ) using Cycle Sort | Function to print array element ; Traverse the array ; Function to sort the array in O ( N ) ; Traverse the array ; If the current element is at correct position ; Else swap the current element with it 's correct position ; Swap the value of arr [ i ] and arr [ arr [ i ] - 1 ] ; Driver code ; Function call to sort the array ; Function call to print the array
def printArray ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT def sortArray ( arr , N ) : NEW_LINE INDENT i = 0 NEW_LINE while i < N : NEW_LINE INDENT if arr [ i ] == i + 1 : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp1 = arr [ i ] NEW_LINE temp2 = arr [ arr [ i ] - 1 ] NEW_LINE arr [ i ] = temp2 NEW_LINE arr [ temp1 - 1 ] = temp1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 5 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE sortArray ( arr , N ) NEW_LINE printArray ( arr , N ) NEW_LINE DEDENT