Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted.
Examples:
Input : arr[] = {10, 4, 11, 7, 6, 20}
k = 2;
Output : arr[] = {4, 6, 11, 7, 10, 20}
Input : arr[] = {30, 20, 10}
k = 0
Output : arr[] = {30, 10, 20}
A simple solution is to copy all elements except k-th of a given array to another array. Then sort the other array using a sorting algorithm. Finally, again copy the sorted array to the original array. While copying, skip k-th element.
C++
#include <bits/stdc++.h>
using namespace std;
void sortExceptK( int arr[], int n, int k) {
int temp[n - 1], index = 0;
for ( int i = 0; i < n; i++) {
if (i != k) {
temp[index++] = arr[i];
}
}
sort(temp, temp + n - 1);
index = 0;
for ( int i = 0; i < n; i++) {
if (i != k) {
arr[i] = temp[index++];
}
}
}
int main() {
int arr[] = { 10, 4, 11, 7, 6, 20 };
int k = 2;
int n = sizeof (arr) / sizeof (arr[0]);
sortExceptK(arr, n, k);
for ( int i = 0; i < n; i++) {
cout << arr[i] << " " ;
}
return 0;
}
|
Time Complexity: O(n*log2n) as sorting takes n*log2n time.
Space Complexity: O(n) as temp array has been created.
Below is an efficient solution.
- Swap k-th element with the last element.
- Sort all elements except the last.
- For every element from (k+1)-th to last, move them one position ahead.1
- Copy k-th element back to position k.
C++
#include <bits/stdc++.h>
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] << " " ;
}
|
Time Complexity: O(n*log(n)) where n is the number of elements.
Auxiliary Space: O(1)
Please refer complete article on Sorting all array elements except one for more details!