Sorting Algorithms
bubble sort
The bubbleSort()
function sorts an array by repeatedly stepping through the list,
comparing adjacent items, and swapping them if they are in the wrong order. This process is repeated until the array is sorted.
This custom implementation demonstrates the bubble sort algorithm, where the outer loop ensures that each pass moves the largest element to its correct position. The process is optimized by checking whether any elements were swapped in the inner loop, allowing the algorithm to break early if the array is already sorted.
function bubbleSort(array) {
const n = array.length;
for (let i = 0; i < n - 1; i++) {
let swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
[array[j], array[j + 1]] = [array[j + 1], array[j]];
swapped = true;
}
}
if (!swapped) {
break;
}
}
return array;
}
const myArray = [7, 3, 9, 12, 11];
const sortedArray = bubbleSort(myArray);
console.log(sortedArray);
// [ 3, 7, 9, 11, 12 ]
insertion sort
The insertionSort()
function sorts an array by
repeatedly picking the next element and inserting it into the correct position within the already sorted portion of the array.
It builds the sorted array one item at a time by comparing the current item to the previous ones.
This custom implementation demonstrates the insertion sort algorithm. For each element, it is compared to the previous ones and inserted into the correct position, shifting elements as necessary.
function insertionSort(array) {
const n = array.length;
for (let i = 1; i < n; i++) {
let insertIndex = i;
const currentValue = array[i];
for (let j = i - 1; j >= 0; j--) {
if (array[j] > currentValue) {
array[j + 1] = array[j];
insertIndex = j;
} else {
break;
}
}
array[insertIndex] = currentValue;
}
return array;
}
const myArray = [64, 34, 25, 12, 22, 11, 90, 5];
const sortedArray = insertionSort(myArray);
console.log(sortedArray);
// [ 5, 11, 12, 22, 25, 34, 64, 90 ]
selection sort
The selectionSort()
algorithm sorts an
array by repeatedly finding the smallest element from the unsorted part and swapping it with the element at
the current position. It iterates through the array, and in each iteration, selects the smallest element from
the remaining unsorted portion and moves it to its correct position.
This custom implementation demonstrates the selection sort algorithm by scanning the array for the smallest element and swapping it to the front, progressively moving through the array.
const selectionSort = (arr) => {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
const minValue = arr.splice(minIndex, 1)[0];
arr.splice(i, 0, minValue);
}
};
const myArray = [64, 34, 25, 5, 22, 11, 90, 12];
selectionSort(myArray);
console.log(myArray);
// [ 5, 11, 12, 22, 25, 34, 64, 90 ]