Jaconir

Sorting Algorithms

Learn how different algorithms arrange data into a specific order, a fundamental concept in computer science.

Why is Sorting Important?

Sorting is the process of arranging items in a collection in a specific order (e.g., numerical or alphabetical). It might seem basic, but it's one of the most important concepts in computer science. Many advanced algorithms, like binary search, require a sorted collection to work efficiently. Understanding different sorting algorithms and their trade-offs in terms of time and space complexity is crucial for writing efficient and scalable code.

In this guide, we'll explore some of the most common sorting algorithms. Use the interactive visualizer below to see how each one works step-by-step.

Interactive Sorting Visualizer
An unsorted array of numbers is provided. Select an algorithm and use the controls to see how it works step-by-step.
64
34
25
12
22
11
90
Select an algorithm to start.
Algorithm Complexity
A comparison of the time and space complexity for common sorting algorithms.
AlgorithmBest TimeAverage TimeWorst TimeSpace
Bubble Sort
O(n)
O(n²)
O(n²)
O(1)
Selection Sort
O(n²)
O(n²)
O(n²)
O(1)
Merge Sort
O(n log n)
O(n log n)
O(n log n)
O(n)
Interview Problems
See how sorting is used as a tool to solve common interview questions.

The Problem: Given an array of strings, group the anagrams together.
The Insight: Anagrams become identical when their letters are sorted alphabetically (e.g., "eat", "tea", and "ate" all become "aet"). This sorted string makes a perfect key for a hash map to group the original words.

Input: ["eat","tea","tan","ate","nat","bat"]
Current Word: N/A
Sorted Key: N/A
{}
Start with an empty hash map. Iterate through the words.
groupAnagrams.js
function groupAnagrams(strs) {
    const map = {};
    for (let str of strs) {
        // Create a key by sorting the string's characters
        const sorted = str.split('').sort().join('');
        // If the key doesn't exist, initialize an array
        if (!map[sorted]) {
            map[sorted] = [];
        }
        // Push the original string to the group
        map[sorted].push(str);
    }
    // Return the values of the map
    return Object.values(map);
};
Coding Challenge
Given an array `nums` with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
Go Deeper with "Grokking Algorithms"

For a fantastically illustrated and easy-to-understand guide to algorithms and data structures like sorting, "Grokking Algorithms" by Aditya Bhargava is an unbeatable resource.

J
Dafin Edison J
Creator & Developer of Jaconir

I build things for the web. From immersive games to practical tools, my goal is to create products that people love to use and to share the knowledge I've gained along the way.