Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
- Store the first element in a variable
- Extract and sort the remaining elements using
slice(1)andsort() - Add the first element back to the beginning using
unshift() - 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.
