VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sorting-array-elements-except-one/

⇱ Sorting all array elements except one - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorting all array elements except one

Last Updated : 7 Jun, 2026

Given an array arr[] and an integer k, sort the array in ascending order while keeping the element at index k fixed at its original position. Return the resulting array.

Examples:

Input: arr[] = [10, 4, 11, 7, 6, 20], k = 2
Output: [4, 6, 11, 7, 10, 20]
Explanation: The element 11 at index 2 remains fixed, while all other elements are sorted in ascending order.

Input: arr[] = [30, 20, 10], k = 0
Output: [30, 10, 20]
Explanation: The element 30 at index 0 remains fixed, while the remaining elements are sorted in ascending order.

[Naive Approach] Using Temporary Array - O(n log n) Time O(n) Space

The idea is to keep the element at index k fixed and store all the remaining elements in a temporary array. Sort the temporary array and place the sorted elements back into the original array while skipping index k. This ensures that the element at index k remains unchanged and all other elements are sorted in ascending order.


Output
[30, 10, 20]

Time Complexity: O(n log n)
Auxiliary Space: O(n)

[Expected Approach] Move to End and Sort In-Place - O(n log n) Time O(1) Space

The idea is to temporarily move the element at index k to the end.. Then, sort the first n - 1 elements. Finally, move the fixed element back to its original position by repeatedly swapping it with its previous element. This sorts all elements except the one at index k while using constant extra space.


Output
[30, 10, 20]

Time Complexity: O(n log n)
Auxiliary Space: O(1)

Comment
Article Tags: