Animated Algorithm Playground Swift Script

This Swift script visually demonstrates the bubble sort algorithm by animating each step in the terminal as it sorts a randomly generated array of numbers from unsorted to sorted order.

Click to view script…
#!/usr/bin/env swift

import Foundation

// Function to clear the terminal screen using ANSI escape codes.
func clearScreen() {
    print("\u{001B}[2J", terminator: "")
    print("\u{001B}[H", terminator: "")
}

// Function to display the array as bars with their values.
func displayArray(_ arr: [Int]) {
    for value in arr {
        let bar = String(repeating: "▇", count: value)
        print("\(bar) (\(value))")
    }
}

// Generate an array of 20 random integers between 1 and 20.
var numbers = (0..<20).map { _ in Int.random(in: 1...20) }

// Show the initial unsorted array.
clearScreen()
print("Initial Array:")
displayArray(numbers)
print("\nPress Enter to start the animated bubble sort...")
_ = readLine()

// Bubble sort with animation.
let n = numbers.count

for i in 0..<n {
    var didSwap = false
    for j in 0..<n - i - 1 {
        if numbers[j] > numbers[j + 1] {
            numbers.swapAt(j, j + 1)
            didSwap = true

            // Clear screen and show the current state of the array.
            clearScreen()
            print("Bubble Sort Animation - Pass \(i + 1), Swap at index \(j) and \(j + 1):")
            displayArray(numbers)
            usleep(200000) // Pause for 0.2 seconds
        }
    }
    // If no swaps occurred, the array is sorted.
    if !didSwap {
        break
    }
}

// Final sorted array.
clearScreen()
print("Sorted Array:")
displayArray(numbers)
print("\nSorting complete!")