text: Sort an Array which contain 1 to N values in O ( N ) using Cycle Sort | C ++ program for the above approach ; Function to swap two a & b value ; 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 ; Driver Code ; Function call to sort the array ; Function call to print the array
code: #include " bits / stdc + + . h " NEW_LINE using namespace std ; void swap ( int * a , int * b ) { int temp = * a ; * a = * b ; * b = temp ; } void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << ' ▁ ' ; } } void sortArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; ) { if ( arr [ i ] == i + 1 ) { i ++ ; } else { swap ( & arr [ i ] , & arr [ arr [ i ] - 1 ] ) ; } } } int main ( ) { int arr [ ] = { 2 , 1 , 5 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArray ( arr , N ) ; printArray ( arr , N ) ; return 0 ; }