Sorting all array elements except one | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sortExceptK ( int arr [ ] , int k , int n ) { swap ( arr [ k ] , arr [ n - 1 ] ) ; sort ( arr , arr + n - 1 ) ; int last = arr [ n - 1 ] ; for ( int i = n - 1 ; i > k ; i -- ) arr [ i ] = arr [ i - 1 ] ; arr [ k ] = last ; } int main ( ) { int a [ ] = { 10 , 4 , 11 , 7 , 6 , 20 } ; int k = 2 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; sortExceptK ( a , k , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " ▁ " ; }