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
Sorting Array without using sort() in JavaScript
Sorting arrays without using the built-in sort() method is a common programming challenge that helps understand sorting algorithms. JavaScript provides several approaches to implement custom sorting logic.
Using Array.reduce() for Insertion Sort
The reduce() method can implement insertion sort by building a sorted array incrementally:
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
const sortWithReduce = arr => {
return arr.reduce((acc, val) => {
let ind = 0;
while(ind acc[ind]){
ind++;
}
acc.splice(ind, 0, val);
return acc;
}, []);
};
console.log("Original:", arr);
console.log("Sorted:", sortWithReduce(arr));
Original: [4, 56, 5, 3, 34, 37, 89, 57, 98] Sorted: [3, 4, 5, 34, 37, 56, 57, 89, 98]
Bubble Sort Implementation
Bubble sort repeatedly compares adjacent elements and swaps them if they're in wrong order:
function bubbleSort(arr) {
const sortedArr = [...arr]; // Create copy to avoid mutation
for (let i = 0; i sortedArr[j + 1]) {
// Swap elements
[sortedArr[j], sortedArr[j + 1]] = [sortedArr[j + 1], sortedArr[j]];
}
}
}
return sortedArr;
}
const numbers = [64, 34, 25, 12, 22, 11, 90];
console.log("Bubble sort result:", bubbleSort(numbers));
Bubble sort result: [11, 12, 22, 25, 34, 64, 90]
Selection Sort Implementation
Selection sort finds the minimum element and places it at the beginning:
function selectionSort(arr) {
const sortedArr = [...arr];
for (let i = 0; i
Selection sort result: [10, 13, 14, 29, 37]
Comparison of Sorting Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Reduce (Insertion) | O(n²) | O(n) | Small arrays, functional style |
| Bubble Sort | O(n²) | O(1) | Educational purposes |
| Selection Sort | O(n²) | O(1) | Memory-constrained environments |
Recursive Quick Sort
For better performance on larger arrays, quick sort divides the array around a pivot:
function quickSort(arr) {
if (arr.length x x === pivot);
const right = arr.filter(x => x > pivot);
return [...quickSort(left), ...middle, ...quickSort(right)];
}
const largeArray = [3, 6, 8, 10, 1, 2, 1];
console.log("Quick sort result:", quickSort(largeArray));
Quick sort result: [1, 1, 2, 3, 6, 8, 10]
Conclusion
Multiple approaches exist for sorting without sort(). Use reduce() for functional style, bubble/selection sort for learning, and quick sort for better performance on larger datasets.
