Sort an almost sorted array where only two elements are swapped | This function sorts an array that can be sorted by single swap ; Traverse the given array from rightmost side ; Check if arr [ i ] is not in order ; Find the other element to be swapped with arr [ i ] ; Swap the pair ; A utility function to print an array of size n ; Driver Code
< ? php function sortByOneSwap ( & $ arr , $ n ) { for ( $ i = $ n - 1 ; $ i > 0 ; $ i -- ) { if ( $ arr [ $ i ] < $ arr [ $ i - 1 ] ) { $ j = $ i - 1 ; while ( $ j >= 0 && $ arr [ $ i ] < $ arr [ $ j ] ) $ j -- ; $ temp = $ arr [ $ i ] ; $ arr [ $ i ] = $ arr [ $ j + 1 ] ; $ arr [ $ j + 1 ] = $ temp ; break ; } } } function printArray ( & $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo " STRNEWLINE " ; } $ arr = array ( 10 , 30 , 20 , 40 , 50 , 60 , 70 ) ; $ n = sizeof ( $ arr ) ; echo " Given ▁ array ▁ is ▁ " . " STRNEWLINE " ; printArray ( $ arr , $ n ) ; sortByOneSwap ( $ arr , $ n ) ; echo " Sorted ▁ array ▁ is ▁ " . " STRNEWLINE " ; printArray ( $ arr , $ n ) ;