Sorting all array elements except one | PHP 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 ; Driver code
< ? php function sortExceptK ( & $ arr , $ k , $ n ) { $ t = $ arr [ $ k ] ; $ arr [ $ k ] = $ arr [ $ n - 1 ] ; $ arr [ $ n - 1 ] = $ t ; $ t = $ arr [ count ( $ arr ) - 1 ] ; $ arr = array_slice ( $ arr , 0 , -1 ) ; sort ( $ arr ) ; array_push ( $ arr , $ t ) ; $ last = $ arr [ $ n - 1 ] ; for ( $ i = $ n - 1 ; $ i > $ k ; $ i -- ) $ arr [ $ i ] = $ arr [ $ i - 1 ] ; $ arr [ $ k ] = $ last ; } $ a = array ( 10 , 4 , 11 , 7 , 6 , 20 ) ; $ k = 2 ; $ n = count ( $ a ) ; sortExceptK ( $ a , $ k , $ n ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo ( $ a [ $ i ] . " ▁ " ) ; ? >