/VisualSort

An animated visualization of sorting algorithms.

Primary LanguageJavaScript

VisualSort

An animated visualization of sorting algorithms.

Algorithms

Animated

  • Bubble Sort
  • Comb Sort
  • Heap Sort
  • Insertion Sort
  • Selection Sort
  • Shell Sort

Implemented

  • Merge Sort

To Do

  • Counting Sort

How Does It Work

Animation Object

The animation object contains the frames which hold the indices of the elements to be highlighted and/or swapped.

The frames are essentially the stored "steps" of the algorithm.

animation = {
    "frames":[
        {
            "elements":[],
            "highlights":[0, 1]
        },
        {
            "elements":[0, 1],
            "highlights":[0, 1]
        }
        .
        .
    ]
}

Usage

The animation object is created in a sorting algorithm.
Particular events are stored as frames of the animation.

class Algorithms {
    static bubble(e, order) {
        let elements = e;
        let solution = new Animation();
        let swapped = false;

        for (let i = 0; i < elements.length; ++i) {
            swapped = false;
            for (let j = 0; j < elements.length - 1; ++j) {
                solution.addFrame(new Frame([], [j, j + 1])); // Record to-be-highlighted elements

                if (order == "desc" ? elements[j] < elements[j + 1] : elements[j] > elements[j + 1]) {
                    swapped = true;

                    const temp = elements[j];
                    elements[j] = elements[j + 1];
                    elements[j + 1] = temp;

                    solution.addFrame(new Frame([j, j + 1], [j, j + 1])); // Record to-be-swapped & to-be-highlighted elements
                }
            }

            if (!swapped) {
                break;
            }
        }
        return solution;
    }
}

Animating the Algorithm

The animation is played by a function that highlights the current elements in a frame and/or swaps them.

Target Changes

  • Refine Swap Animation
  • Algorithm Comparison
  • Custom Sort Order (Ascending or Descending)
  • Algorithm Details

References