Problem Statement: Given an array A of positive integers, sort the array in ascending order such that element at index K in unsorted array stays unmoved and all other elements are sorted.
static int sortExceptK(int arr[], int k, int n)
{
// Move k-th element to end of array.
int temp = arr[k];
arr[k] = arr[n-1];
arr[n-1] = temp;
// Sort all elements except last one.
Arrays.sort(arr, 0, n-1); // From import java.util.Arrays;
// Store last element (originally k-th)
int last = arr[n-1];
// Move all elements from k-th to one
// position ahead.
for (int i = n-1; i > k; i--)
arr[i] = arr[i-1];
// Restore k-th element
arr[k] = last;
return 0;
}
static int sortExceptK(int arr[], int k, int n)
{
// Move k-th element to end of array.
int temp = arr[k];
arr[k] = arr[n-1];
arr[n-1] = temp;
// Sort all elements except last one.
Arrays.sort(arr, 0, n-1); // From import java.util.Arrays;
// Store last element (originally k-th)
int last = arr[n-1];
// Move all elements from k-th to one
// position ahead.
for (int i = n-1; i > k; i--)
arr[i] = arr[i-1];
// Restore k-th element
arr[k] = last;
return 0;
}