Algorithms
🎯 Introduction
These basic algorithms help you understand how programs process data, improve code efficiency, and build faster frontend applications. You will be better equipped to sort data and quickly find a target within it.
🧮 Sorting Algorithms Explained
Sorting is a fundamental part of frontend development. It turns unordered data into ordered data, whether you are sorting product prices or arranging a timeline.
Let's explore several classic, widely used sorting algorithms.
Bubble Sort
Bubble sort is one of the simplest sorting algorithms. It compares adjacent elements from beginning to end, moving larger values toward the end of the array.
Picture bubbles rising through water, with larger bubbles floating toward the surface.
function bubbleSort(arr) {
let len = arr.length;
for (let i = 0; i < len - 1; i++) {
for (let j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
bubbleSort([5, 4, 2, 1, 3]); // [ 1, 2, 3, 4, 5 ]
Selection Sort
Selection sort repeatedly finds the smallest element in the remaining unsorted portion and places it at the front of that portion.
Imagine choosing apples: each time, you pick the smallest remaining apple and set it aside.
function selectionSort(arr) {
let len = arr.length;
for (let i = 0; i < len - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
selectionSort([5, 4, 2, 1, 3]); // [ 1, 2, 3, 4, 5 ]
Insertion Sort
Insertion sort divides the array into sorted and unsorted portions. It takes the first unsorted element and inserts it into the correct position in the sorted portion.
It is like arranging playing cards by inserting each new card into its proper place.
function insertionSort(arr) {
let len = arr.length;
for (let i = 1; i < len; i++) {
let key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}
insertionSort([5, 4, 2, 1, 3]); // [ 1, 2, 3, 4, 5 ]
Quick Sort
Quick sort uses divide and conquer. It partitions the array around a pivot into smaller values and larger or equal values, then recursively sorts each portion.
Imagine dividing teams into two groups by ability, then determining the results within each group.
function quickSort(arr) {
if (arr.length <= 1) return arr;
let pivot = arr[arr.length - 1];
let left = [];
let right = [];
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
quickSort([5, 4, 2, 1, 3]); // [ 1, 2, 3, 4, 5 ]
Merge Sort
Merge sort also uses divide and conquer: split the array in two, sort each half, then merge them. It is a useful way to understand recursive structures.
Think of dividing a large puzzle into smaller sections, completing each section, and combining them.
function mergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
function merge(left, right) {
let result = [];
let i = 0,
j = 0;
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
result.push(left[i++]);
} else {
result.push(right[j++]);
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}
mergeSort([5, 4, 2, 1, 3]); // [ 1, 2, 3, 4, 5 ]
🔍 Searching Algorithms Explained
Searching is a common frontend operation, such as finding a user in a list or locating a record.
Linear Search
Linear search is the simplest search method: visit elements one by one and return when the target is found.
It is like looking for a sentence in a book by reading one page at a time.
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
linearSearch([5, 4, 2, 1, 3], 1); // 3
Binary Search
Binary search works on sorted arrays. It checks the middle element, determines which side may contain the target, and repeatedly narrows the range.
It is like looking up a word in a dictionary: open to the middle, compare entries, and narrow the search range.
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
binarySearch([1, 2, 3, 4, 5], 3); // 2
❓ Questions and Answers
Q1: Why is bubble sort inefficient?
It requires many comparisons and swaps. Its O(n²) time complexity makes it slow for large datasets.
Q2: Can binary search work on an unsorted array?
No. Binary search requires a sorted array so that comparisons reliably identify which half may contain the target.
🎉 You have learned basic algorithms including bubble sort, quick sort, and binary search! Use them to write more efficient frontend programs!
Data Structures
Explore common frontend data structures with JavaScript examples covering the fundamentals and implementations of arrays, linked lists, stacks, queues, hash tables, trees, and graphs.
Algorithmic Techniques
Explore recursion, divide and conquer, greedy algorithms, dynamic programming, and two-pointer sliding windows through simple explanations and common frontend scenarios.
