Learn to implement and apply basic sorting algorithms: Bubble Sort and Insertion Sort.
function bubbleSort(arr) {
const len = arr.length;
let swapped;
do {
swapped = false;
for (let i = 0; i < len - 1; i++) {
if (arr[i] > arr[i + 1]) {
// Swap elements
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
} while (swapped);
return arr;
}
const numbers = [64, 34, 25, 12, 22, 11, 90];
console.log(bubbleSort(numbers)); // [11, 12, 22, 25, 34, 64, 90]
function insertionSort(arr) {
const len = arr.length;
for (let i = 1; i < len; i++) {
// Store the current element to be compared
let current = arr[i];
let j = i - 1;
// Compare current with sorted elements and shift them to make space
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
// Place current in the correct position
arr[j + 1] = current;
}
return arr;
}
const numbers = [12, 11, 13, 5, 6];
console.log(insertionSort(numbers)); // [5, 6, 11, 12, 13]
Algorithm | Best Case | Average Case | Worst Case | Space | Stable |
---|---|---|---|---|---|
Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
Modify the bubble sort algorithm to skip comparisons for already sorted elements at the end of the array.
function optimizedBubbleSort(arr) {
// Your code here
}
Extend insertion sort to work with an array of objects, sorting by a specified property.
function insertionSortByProperty(array, propertyName) {
// Your code here
}
const people = [
{ name: 'John', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
console.log(insertionSortByProperty(people, 'age'));
// Output: [{ name: 'Alice', age: 25 }, { name: 'John', age: 30 }, { name: 'Bob', age: 35 }]
If you want more practice with sorting algorithms, check out these resources: