Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Essential JavaScript Algorithms for Sorting, String Manipulation, and Search

Tools Apr 22 11

Sorting Algorithms

Bubble Sort

A simple comparison-based algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

function bubbleSort(sequence) {
  const length = sequence.length;
  for (let pass = 0; pass < length - 1; pass++) {
    for (let idx = 0; idx < length - pass - 1; idx++) {
      if (sequence[idx] > sequence[idx + 1]) {
        [sequence[idx], sequence[idx + 1]] = [sequence[idx + 1], sequence[idx]];
      }
    }
  }
  return sequence;
}

Insertion Sort

Builds the final sorted array one item at a time by inserting each new element into its correct position within the already-sorted portion.

function insertionSort(sequence) {
  for (let i = 1; i < sequence.length; i++) {
    const current = sequence[i];
    let j = i - 1;
    while (j >= 0 && sequence[j] > current) {
      sequence[j + 1] = sequence[j];
      j--;
    }
    sequence[j + 1] = current;
  }
  return sequence;
}

Quick Sort (In-Place Partition)

A divide-and-conquer algorithm that selects a 'pivot', partitions the array around it so smaller elements go left and larger ones right, then recursive sorts both partitions.

function quickSort(arr, low = 0, high = arr.length - 1) {
  if (low < high) {
    const pivotIndex = partition(arr, low, high);
    quickSort(arr, low, pivotIndex - 1);
    quickSort(arr, pivotIndex + 1, high);
  }
  return arr;
}

function partition(arr, left, right) {
  const pivot = arr[right];
  let storeIdx = left;

  for (let i = left; i < right; i++) {
    if (arr[i] < pivot) {
      [arr[i], arr[storeIdx]] = [arr[storeIdx], arr[i]];
      storeIdx++;
    }
  }
  [arr[storeIdx], arr[right]] = [arr[right], arr[storeIdx]];
  return storeIdx;
}

String Operations

Palindrome Detection

Checks whether a string reads the same forwards and backwards after normalizing case and removing non-alphanumeric characters.

function isPalindrome(input) {
  const cleaned = input.toLowerCase().replace(/[^a-z0-9]/g, '');
  const reversed = cleaned.split('').reverse().join('');
  return cleaned === reversed;
}

Reverse a String

Reverses the character order of a given string.

function reverseText(str) {
  return str.split('').reverse().join('');
}

Most Frequent Character

Finds the character appearing most often in a string.

function mostCommonChar(text) {
  const frequency = {};
  let dominant = '';
  
  for (const char of text) {
    frequency[char] = (frequency[char] || 0) + 1;
    if (!dominant || frequency[char] > frequency[dominant]) {
      dominant = char;
    }
  }
  
  return dominant;
}

Array Utilities

Remove Duplicates

Eliminates repeated values from an array using either a Set or filtering logic.

function deduplicate(array) {
  return [...new Set(array)];
}

// Alternative with filter
function deduplicateByFilter(array) {
  return array.filter((item, index) => array.indexOf(item) === index);
}

Search Algorithms

Binary Search

Efficiently locates a target value within a sorted array by repeatedly dividing the search interval in half.

function binarySearch(sortedArr, target, start = 0, end = sortedArr.length - 1) {
  if (start > end) return -1;
  
  const mid = Math.floor((start + end) / 2);
  
  if (sortedArr[mid] === target) return mid;
  if (sortedArr[mid] > target) {
    return binarySearch(sortedArr, target, start, mid - 1);
  }
  return binarySearch(sortedArr, target, mid + 1, end);
}

Tree Traversal

Depth-First Search (Iterative)

Uses a stack to explore as far as possible along each branch before backtracking.

function dfsIterative(root) {
  if (!root) return [];
  
  const result = [];
  const stack = [root];
  
  while (stack.length > 0) {
    const node = stack.pop();
    result.push(node);
    
    // Push children in reverse order to maintain left-to-right traversal
    for (let i = node.children.length - 1; i >= 0; i--) {
      stack.push(node.children[i]);
    }
  }
  
  return result;
}

Breadth-First Search (Iterative)

Uses a queue to visit nodes level-by-level, starting from the root.

function bfsIterative(root) {
  if (!root) return [];
  
  const result = [];
  const queue = [root];
  
  while (queue.length > 0) {
    const node = queue.shift();
    result.push(node);
    
    for (const child of node.children) {
      queue.push(child);
    }
  }
  
  return result;
}

Custom Sorting with Array.prototype.sort

The built-in sort() method accepts a comparator function to define custom ordering. Without one, it converts elements to strings and compares their UTF-16 code units — leading to unexpected behavior for numbers or mixed-case strings.

// Correct numeric sort
[10, 20, 1, 2].sort((a, b) => a - b); // [1, 2, 10, 20]

// Case-insensitive string sort
['Apple', 'banana', 'Cherry'].sort((a, b) => 
  a.toLowerCase().localeCompare(b.toLowerCase())
); // ['Apple', 'banana', 'Cherry']

// Sort objects by property
const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 }
];
users.sort((a, b) => a.age - b.age);

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Capturing Android Screenshots and Screen Recordings with ADB

Two practical ways to grab images and videos from an Android device: Mirror the phone display to a computer and use desktop tools for screenshots and GIFs Use ADB commands (no UI mirroring required)...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.