JavaScript Sorting Algorithms - Explanations,
Code & Practice
Built-in sort()
Ascending and descending numeric sorting.
Code
const arr=[5,2,8,1,9];
[Link]((a,b)=>a-b); // [1,2,5,8,9]
[Link]((a,b)=>b-a); // [9,8,5,2,1]
Practice
1. Sort [10,3,7,1]. 2. Sort an array of objects by age. 3. Why does sort() fail without a comparator for
numbers?
Bubble Sort
Compare adjacent elements and swap.
Code
function bubbleSort(arr){
for(let i=0;i<[Link]-1;i++){
for(let j=0;j<[Link]-i-1;j++){
if(arr[j]>arr[j+1]){
[arr[j],arr[j+1]]=[arr[j+1],arr[j]];
}
}
}
return arr;
}
Practice
Dry run bubbleSort([4,1,3,2]). Count the number of swaps.
Selection Sort
Select the minimum and place it at the beginning.
Code
function selectionSort(arr){
for(let i=0;i<[Link]-1;i++){
let min=i;
for(let j=i+1;j<[Link];j++){
if(arr[j]<arr[min]) min=j;
}
[arr[i],arr[min]]=[arr[min],arr[i]];
}
return arr;
}
Practice
Implement descending order by selecting the maximum element.
Insertion Sort
Insert each element into the sorted part.
Code
function insertionSort(arr){
for(let i=1;i<[Link];i++){
let cur=arr[i],j=i-1;
while(j>=0 && arr[j]>cur){
arr[j+1]=arr[j]; j--;
}
arr[j+1]=cur;
}
return arr;
}
Practice
Trace insertionSort([9,5,1,4]).
Merge Sort
Divide and conquer. O(n log n).
Code
Pseudo-code: Split array -> Sort halves -> Merge.
Practice
Write merge(left,right) and test with [5,2,8,1].
Quick Sort
Choose a pivot and partition.
Code
Pseudo-code: Pivot -> Left < Pivot -> Right > Pivot -> Recurse.
Practice
Choose different pivots and compare recursion.
Min / Max
Find minimum and maximum without sorting.
Code
let min=arr[0],max=arr[0];
for(const n of arr){
if(n<min) min=n;
if(n>max) max=n;
}
Practice
Find second largest and second smallest without sort().