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
function sortByOneSwap ( arr , n ) { for ( let i = n - 1 ; i > 0 ; i -- ) { if ( arr [ i ] < arr [ i - 1 ] ) { let j = i - 1 ; while ( j >= 0 && arr [ i ] < arr [ j ] ) j -- ; let temp = arr [ i ] ; arr [ i ] = arr [ j + 1 ] ; arr [ j + 1 ] = temp ; break ; } } } function printArray ( arr , n ) { let i ; for ( i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( " " ) ; } let arr = [ 10 , 30 , 20 , 40 , 50 , 60 , 70 ] ; let n = arr . length ; document . write ( " " + " " ) ; printArray ( arr , n ) ; sortByOneSwap ( arr , n ) ; document . write ( " " + " " ) ; printArray ( arr , n ) ;