Sorting all array elements except one | Javascript program to sort all elements except element at index k . ; Move k - th element to end ; Sort all elements except last ; Store last element ( originally k - th ) ; Move all elements from k - th to one position ahead . ; Restore k - th element ; Move k - th element to end
function sortExceptK ( arr , k , n ) { let temp = arr [ k ] ; arr [ k ] = arr [ n - 1 ] ; arr [ n - 1 ] = temp ; arr . sort ( function ( a , b ) { return a - b } ) ; let last = arr [ n - 1 ] ; for ( let i = n - 1 ; i > k ; i -- ) arr [ i ] = arr [ i - 1 ] ; arr [ k ] = last ; temp = arr [ k ] ; arr [ k ] = arr [ n - 1 ] ; arr [ n - 1 ] = temp ; return 0 ; } let a = [ 10 , 4 , 11 , 7 , 6 , 20 ] ; let k = 2 ; let n = a . length ; sortExceptK ( a , k , n ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( a [ i ] + " " ) ;