Sort first k values in ascending order and remaining n | C ++ program to sort first k elements in increasing order and remaining n - k elements in decreasing ; Function to sort the array ; Store the k elements in an array ; Store the remaining n - k elements in an array ; sorting the array from 0 to k - 1 places ; sorting the array from k to n places ; storing the values in the final array arr ; printing the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printOrder ( int arr [ ] , int n , int k ) { int len1 = k , len2 = n - k ; int arr1 [ k ] , arr2 [ n - k ] ; for ( int i = 0 ; i < k ; i ++ ) arr1 [ i ] = arr [ i ] ; for ( int i = k ; i < n ; i ++ ) arr2 [ i - k ] = arr [ i ] ; sort ( arr1 , arr1 + len1 ) ; sort ( arr2 , arr2 + len2 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < k ) arr [ i ] = arr1 [ i ] ; else { arr [ i ] = arr2 [ len2 - 1 ] ; len2 -- ; } } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , -1 } ; int k = 4 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printOrder ( arr , n , k ) ; return 0 ; }