JavaScript Sorting Algorithms with Examples
1. Built-in sort()
Ascending:
const arr = [5,2,8,1,9];
[Link]((a,b)=>a-b);
Output: [1,2,5,8,9]
Descending:
[Link]((a,b)=>b-a);
Output: [9,8,5,2,1]
Time: O(n log n) (implementation dependent).
2. Bubble Sort
Example:
[5,2,8,1]
Pass 1:
5↔2 -> [2,5,8,1]
8↔1 -> [2,5,1,8]
Pass 2:
5↔1 -> [2,1,5,8]
Pass 3:
2↔1 -> [1,2,5,8]
Time: O(n²)
Space: O(1)
Use: Educational, small datasets.
3. Selection Sort
Find the smallest value and place it first.
Example:
[5,2,8,1]
Pass 1 -> 1 selected
[1,2,8,5]
Pass 2 -> 2 already correct
Pass 3 -> 5 selected
Result:
[1,2,5,8]
Time: O(n²)
Space: O(1)
4. Insertion Sort
Example:
[5,2,8,1]
Insert 2:
[2,5,8,1]
Insert 8:
[2,5,8,1]
Insert 1:
[1,2,5,8]
Best: O(n)
Worst: O(n²)
Good for nearly sorted arrays.
5. Merge Sort
Divide:
[5,2,8,1]
-> [5,2] [8,1]
-> [5][2][8][1]
Merge:
[2,5]
[1,8]
Final:
[1,2,5,8]
Time: O(n log n)
Space: O(n)
Very common interview question.
6. Quick Sort
Choose Pivot = 5
Less:
[2,1]
Greater:
[8]
Sort recursively
Result:
[1,2,5,8]
Average: O(n log n)
Worst: O(n²)
Used in many libraries.
7. Find Minimum
let arr=[5,2,8,1];
let min=arr[0];
for(const num of arr){
if(num<min)
min=num;
}
Output:
1
Time: O(n)
8. Find Maximum
let arr=[5,2,8,1];
let max=arr[0];
for(const num of arr){
if(num>max)
max=num;
}
Output:
8
Time: O(n)
Interview Comparison
Bubble Sort
• Easy to learn
• O(n²)
Selection Sort
• Fewer swaps
• O(n²)
Insertion Sort
• Best for nearly sorted arrays
• O(n²)
Merge Sort
• Stable
• O(n log n)
Quick Sort
• Fast average case
• O(n log n) average
Built-in sort()
• Best for day-to-day JavaScript coding.