Sorting Algorithm Visualizer (6 Algorithms)

Observe the different approaches of six common sorting algorithms simultaneously, or run them individually.

Bubble Sort

for i from 0 to n-1:
  for j from 0 to n-i-2:
    if array[j] > array[j+1]:
      swap(array[j], array[j+1])
                

Insertion Sort

for i from 1 to n-1:
  key = array[i]
  j = i - 1
  // Move key backward by swapping until sorted position is found
  while j >= 0 AND array[j] > array[j+1]:
    swap(array[j], array[j+1])
    j = j - 1
                

Quick Sort

function quick_sort(low, high):
  if low < high:
    pivot_index = partition(low, high)
    quick_sort(low, pivot_index - 1)
    quick_sort(pivot_index + 1, high)

function partition(low, high):
  pivot = array[high]
  i = low - 1
  for j from low to high - 1:
    if array[j] < pivot:
      i++
      swap(array[i], array[j])
  swap(array[i + 1], array[high])
  return i + 1
                

Selection Sort

for i from 0 to n-2:
  min_idx = i
  for j from i+1 to n-1:
    if array[j] < array[min_idx]:
      min_idx = j
  swap(array[i], array[min_idx])
                

Heap Sort

function build_max_heap():
  for i from n/2 - 1 down to 0:
    heapify(n, i)

function heapify(n, i):
  largest = i
  l = 2*i + 1
  r = 2*i + 2
  if l < n AND array[l] > array[largest]:
    largest = l
  if r < n AND array[r] > array[largest]:
    largest = r
  if largest != i:
    swap(array[i], array[largest])
    heapify(n, largest)

build_max_heap()
for i from n-1 down to 1:
  swap(array[0], array[i])
  heapify(i, 0)
                

Merge Sort

function merge_sort(p, r):
  if p < r:
    q = floor((p + r) / 2)
    merge_sort(p, q)
    merge_sort(q + 1, r)
    merge(p, q, r)

function merge(p, q, r):
  // Compares and writes elements from the two sorted
  // sub-arrays back into the main array sequentially.
  // Visualization now shows comparisons and the sequential
  // 'writing' of the sorted result back into the array.