Sort an integer array, keeping first in place in JavaScript

In JavaScript, when you need to sort an integer array while keeping the first element in its original position, you can combine array slicing with the built-in sort method. This approach preserves the first element while sorting the remaining elements.

Understanding the Problem

The task is to sort an integer array in ascending order while keeping the first element at index 0. For example, if you have an array [4, 7, 8, 5, 6, 1, 3], the result should be [4, 1, 3, 5, 6, 7, 8] - notice how 4 remains in the first position while the rest are sorted.

Algorithm

The solution follows these steps:

  1. Store the first element in a variable
  2. Extract and sort the remaining elements using slice(1) and sort()
  3. Add the first element back to the beginning using unshift()
  4. Return the modified array

Implementation

function sortKeepingFirstInPlace(arr) {
    // Store the first element
    const firstElement = arr[0];
    
    // Sort the remaining elements
    const sortedArray = arr.slice(1).sort((a, b) => a - b);
    
    // Insert the first element at the beginning
    sortedArray.unshift(firstElement);
    
    return sortedArray;
}

const array = [30, 10, 40, 20, 50];
const sortedArr = sortKeepingFirstInPlace(array);
console.log("Original array:", array);
console.log("Sorted with first in place:", sortedArr);
Original array: [ 30, 10, 40, 20, 50 ]
Sorted with first in place: [ 30, 10, 20, 40, 50 ]

Alternative Approach

You can also create the result array directly without using unshift():

function sortKeepingFirstInPlace(arr) {
    if (arr.length <= 1) return arr;
    
    // Create new array with first element + sorted remaining elements
    return [arr[0], ...arr.slice(1).sort((a, b) => a - b)];
}

const numbers = [100, 5, 25, 15, 35, 8];
const result = sortKeepingFirstInPlace(numbers);
console.log("Result:", result);
Result: [ 100, 5, 8, 15, 25, 35 ]

Time and Space Complexity

Aspect Complexity Explanation
Time Complexity O(n log n) Dominated by the sort operation
Space Complexity O(n) Additional array for sorted elements

Conclusion

This approach efficiently sorts an integer array while preserving the first element's position using JavaScript's built-in array methods. The solution has O(n log n) time complexity and works well for most practical applications.

Updated on: 2026-03-15T23:19:00+05:30

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements