Chapter 3 · Simulation

Sorting Algorithms

← Chapter 3

Ready.

Step: 0valuecompared / movedsorted

    Sorting Algorithms

    Pick an algorithm, press Sort and watch 16 random values (10–99) get sorted. Highlighted bars are the items being compared or moved at that moment; when the run finishes, all bars turn green. New Array generates new values, Cancel stops a running sort, and the speed menu sets the pause between steps.

    Bubble sort

    Compares neighbouring items and swaps them if they are out of order. Each pass moves the largest remaining value to the end.

    Insertion sort

    Takes the next item and moves it left through the sorted prefix until it reaches its place. Efficient on small or nearly sorted inputs.

    Selection sort

    Finds the smallest item in the remaining part and swaps it into the next position of the sorted prefix.

    Merge sort

    Recursively splits the list in two, then merges the sorted halves back together.

    Quick sort

    Chooses a pivot and partitions the values around it; then sorts the left and right parts recursively.

    Counting sort

    Counts how many times each value occurs and rebuilds the sorted output from those counts.

    Radix sort

    Processes the numbers digit by digit, applying a stable counting step for each digit value.

    Bucket sort

    Distributes the values into buckets by value range, sorts each bucket and concatenates the results.

    Heap sort

    Builds a max-heap; then repeatedly moves the root to the end and restores the heap property.

    Shell sort

    Makes insertion-sort-like passes with shrinking gaps; the last pass is an ordinary insertion sort with gap 1.

    Complexity

    AlgorithmBestAverageWorstExtra memory
    BubbleO(n)O(n²)O(n²)O(1)
    InsertionO(n)O(n²)O(n²)O(1)
    SelectionO(n²)O(n²)O(n²)O(1)
    MergeO(n log n)O(n log n)O(n log n)O(n)
    QuickO(n log n)O(n log n)O(n²)O(log n) avg.
    CountingO(n+k)O(n+k)O(n+k)O(n+k)
    RadixO(d(n+k))O(d(n+k))O(d(n+k))O(n+k)
    BucketO(n+k)O(n+k)O(n²)O(n+k)
    Heap sortO(n log n)O(n log n)O(n log n)O(1)
    Shelldepends on gapsdepends on gapsO(n²)O(1)

    The O(n) best case of bubble sort applies to the version with an early exit that stops after a pass without swaps; the animation runs the plain version.