JavaScript Algorithms: Sorting, Searching, and Graph Traversal

JavaScript is a versatile programming language widely used for web development. While it is known for its ability to enhance the interactivity of web pages, JavaScript also provides powerful algorithms for sorting, searching, and graph traversal. These algorithms are essential in solving complex problems efficiently. In this article, we will explore advanced JavaScript algorithms, including sorting algorithms like quicksort and mergesort, searching algorithms like binary search, and graph traversal algorithms like breadth-first search and depth-first search.

Sorting Algorithms

Sorting algorithms play a crucial role in organizing data in a specific order. JavaScript offers several efficient sorting algorithms, two of which are quicksort and mergesort.

Let's take a look at each algorithm and its implementation in JavaScript:

Quicksort

Quicksort is a popular divide-and-conquer sorting algorithm. It works by selecting a pivot element and partitioning the array into two sub-arrays, one with elements smaller than the pivot and the other with elements greater than the pivot. The algorithm is then recursively applied to the sub-arrays.

Example

Below is an example of a Quicksort:

function quicksort(arr) {
   if (arr.length <= 1) {
      return arr;
   }
  
   const pivot = arr[0];
   const left = [];
   const right = [];
  
   for (let i = 1; i < arr.length; i++) {
      if (arr[i] < pivot) {
         left.push(arr[i]);
      } else {
         right.push(arr[i]);
      }
   }
  
   return [...quicksort(left), pivot, ...quicksort(right)];
}

const arr = [5, 2, 9, 1, 7];
console.log(quicksort(arr));
[1, 2, 5, 7, 9]

The quicksort function takes an array as input and recursively applies the quicksort algorithm. It selects the first element as the pivot and creates two sub-arrays, left and right, to hold elements smaller and larger than the pivot, respectively. Finally, it concatenates the sorted left array, the pivot, and the sorted right array to return the sorted array.

Merge Sort

Merge Sort is another efficient sorting algorithm that follows the divide-and-conquer approach. It divides the array into smaller sub-arrays, sorts them, and then merges them back together.

Example

Below is an example of a Merge Sort:

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) {
   const merged = [];
   let leftIndex = 0;
   let rightIndex = 0;
  
   while (leftIndex < left.length && rightIndex < right.length) {
      if (left[leftIndex] < right[rightIndex]) {
         merged.push(left[leftIndex]);
         leftIndex++;
      } else {
         merged.push(right[rightIndex]);
         rightIndex++;
      }
   }
  
   return merged.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
}

const arr = [5, 2, 9, 1, 7];
console.log(mergesort(arr));
[1, 2, 5, 7, 9]

The merge sort function takes an array as input and recursively applies the mergesort algorithm. It divides the array into two halves and recursively sorts them using mergesort. The merge function is used to merge the sorted sub-arrays back together by comparing elements from both arrays and appending them to the merged array in ascending order.

Searching Algorithms

Searching algorithms are used to find a specific element or condition within a given dataset. One of the most efficient searching algorithms is the binary search algorithm.

Binary Search

Binary search is a divide-and-conquer algorithm used to search for a specific element in a sorted array. It repeatedly divides the array in half and compares the target element with the middle element to determine if it should search the left or right half.

Example

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

const arr = [1, 2, 5, 7, 9];
console.log(binarySearch(arr, 7));
3

The binarySearch function takes a sorted array and a target element as input. It uses two pointers to narrow down the search range. In each iteration, it calculates the middle index and compares the target with the middle element. If found, it returns the index; otherwise, it adjusts the search range and continues until the element is found or the range is exhausted.

Graph Traversal Algorithms

Graph traversal algorithms are used to explore or traverse a graph data structure systematically. They can solve various problems, such as finding the shortest path or detecting cycles. Two commonly used graph traversal algorithms are breadth-first search (BFS) and depth-first search (DFS).

Breadth-First Search (BFS)

Breadth-first search is an algorithm that explores all vertices at the current level before moving to the next level. It uses a queue to keep track of vertices to visit next.

Example

function bfs(graph, start) {
   const queue = [start];
   const visited = new Set();
  
   while (queue.length > 0) {
      const vertex = queue.shift();
      
      if (!visited.has(vertex)) {
         console.log(vertex);
         visited.add(vertex);
      
         for (const neighbor of graph[vertex]) {
            if (!visited.has(neighbor)) {
               queue.push(neighbor);
            }
         }
      }
   }
}

const graph = {
   A: ['B', 'C'],
   B: ['A', 'D'],
   C: ['A', 'E'],
   D: ['B'],
   E: ['C']
};

console.log('BFS traversal:');
bfs(graph, 'A');
BFS traversal:
A
B
C
D
E

The bfs function takes a graph represented as an adjacency list and a starting vertex. It uses a queue to process vertices level by level, ensuring all neighbors at the current level are visited before moving deeper.

Depth-First Search (DFS)

Depth-first search explores vertices by going as deep as possible along each branch before backtracking. It can be implemented using recursion or a stack.

Example

function dfs(graph, start, visited = new Set()) {
   console.log(start);
   visited.add(start);
  
   for (const neighbor of graph[start]) {
      if (!visited.has(neighbor)) {
         dfs(graph, neighbor, visited);
      }
   }
}

const graph = {
   A: ['B', 'C'],
   B: ['A', 'D'],
   C: ['A', 'E'],
   D: ['B'],
   E: ['C']
};

console.log('DFS traversal:');
dfs(graph, 'A');
DFS traversal:
A
B
D
C
E

The dfs function recursively explores each vertex and its unvisited neighbors. This creates a depth-first traversal pattern, going as deep as possible before backtracking to explore other branches.

Performance Comparison

Algorithm Time Complexity Space Complexity Best Use Case
Quicksort O(n log n) avg, O(n²) worst O(log n) General purpose sorting
Merge Sort O(n log n) O(n) Stable sorting, large datasets
Binary Search O(log n) O(1) Searching sorted arrays
BFS O(V + E) O(V) Shortest path, level-order
DFS O(V + E) O(V) Path finding, cycle detection

Conclusion

These fundamental algorithms form the backbone of efficient JavaScript programming. Mastering sorting, searching, and graph traversal techniques enables developers to solve complex computational problems with optimal performance and clean, maintainable code.

Updated on: 2026-03-15T23:19:01+05:30

823 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements