Algorithms are step-by-step procedures for solving problems. Understanding common algorithms helps you write more efficient code and solve complex problems.
The binary search algorithm is a fast and efficient way to find the index of a given element in a sorted array. It works by repeatedly dividing the search interval in half, narrowing down the possible locations of the element.A binary search is much faster than a linear search, especially for large arrays, as it has a time complexity of O(log n). However, it requires the array to be sorted beforehand.
const binarySearch = (arr, item) => { let l = 0, r = arr.length - 1; while (l <= r) { const mid = Math.floor((l + r) / 2); const guess = arr[mid]; if (guess === item) return mid; if (guess > item) r = mid - 1; else l = mid + 1; } return -1;};binarySearch([1, 2, 3, 4, 5], 1); // 0binarySearch([1, 2, 3, 4, 5], 5); // 4binarySearch([1, 2, 3, 4, 5], 6); // -1
In order to implement the algorithm, we keep track of the left and right boundaries of the search interval, and repeatedly divide it in half until the element is found or the interval is empty.
This implementation does not account for duplicate values in the array.
Bubble sort is a simple sorting algorithm that repeatedly steps through the array, compares adjacent elements and swaps them if they are in the wrong order. The pass through the array is repeated until the array is sorted.
const bubbleSort = arr => { let swapped = false; const a = [...arr]; for (let i = 1; i < a.length; i++) { swapped = false; for (let j = 0; j < a.length - i; j++) { if (a[j + 1] < a[j]) { [a[j], a[j + 1]] = [a[j + 1], a[j]]; swapped = true; } } if (!swapped) return a; } return a;};bubbleSort([2, 1, 4, 3]); // [1, 2, 3, 4]
Implementation steps:
Declare a variable, swapped, that indicates if any values were swapped during the current iteration
Use the spread operator (...) to clone the original array, arr
Use a for loop to iterate over the elements of the cloned array, terminating before the last element
Use a nested for loop to iterate over the segment of the array between 0 and i, swapping any adjacent out of order elements and setting swapped to true
If swapped is false after an iteration, no more changes are needed, so the cloned array is returned
The algorithm has an average time complexity of O(n^2), where n is the size of the input array.
Selection sort is an in-place comparison sorting algorithm. It divides the input array into a sorted and an unsorted subarray. It then repeatedly finds the minimum element in the unsorted subarray and swaps it with the leftmost element in the unsorted subarray.
const selectionSort = arr => { const a = [...arr]; for (let i = 0; i < a.length; i++) { const min = a .slice(i + 1) .reduce((acc, val, j) => (val < a[acc] ? j + i + 1 : acc), i); if (min !== i) [a[i], a[min]] = [a[min], a[i]]; } return a;};selectionSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5]
Implementation:
Use the spread operator (...) to clone the original array, arr
Use a for loop to iterate over elements in the array
Use Array.prototype.slice() and Array.prototype.reduce() to find the index of the minimum element in the subarray to the right of the current index
Perform a swap, if necessary
The algorithm has an average time complexity of O(n^2), where n is the size of the input array.
const isPrime = n => { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 === 0 || n % 3 === 0) return false; for (let i = 5; i * i <= n; i += 6) { if (n % i === 0 || n % (i + 2) === 0) return false; } return true;};isPrime(17); // trueisPrime(18); // false
// Recursiveconst factorial = n => n <= 1 ? 1 : n * factorial(n - 1);// Iterativeconst factorialIterative = n => { let result = 1; for (let i = 2; i <= n; i++) result *= i; return result;};factorial(5); // 120factorialIterative(5); // 120