Sorthem is a language-agnostic tool that enables you to visualize your sorting algorithms with just a few lines of code.
Sorthem is simple. You have a sorting algorithm, written in whatever language you like. Let's say, a bubble sort implementation in Ruby:
arr = [3, 9, 1, 8, 6, 10, 4, 7, 2, 5]
for i in 0..arr.length - 2 do
for j in 0..arr.length - i - 2 do
left = arr[j]
right = arr[j + 1]
if left > right
arr[j], arr[j + 1] = right, left
end
end
end
Almost all algorithms are made up with basic operations like comparing two values, swapping them, etc.
Sorthem needs to know two things:
- what are the values you're sorting
- what are the operations you're doing in order to sort those values
An all you need to do is to print that information to the standard output.
arr = [3, 9, 1, 8, 6, 10, 4, 7, 2, 5]
# Print the array in the format [ 3 9 1 8 6 10 4 7 2 5 ]
puts "[ #{arr.join(' ')} ]"
for i in 0..arr.length - 2 do
for j in 0..arr.length - i - 2 do
left = arr[j]
right = arr[j + 1]
# Tell Sorthem that you're comparing two values
puts "compare #{j} #{j + 1}"
if left > right
# Tell Sorthem that you're swapping two values
puts "swap #{j} #{j + 1}"
arr[j], arr[j + 1] = right, left
end
end
end
With these three lines of code, you now have a visualizer for your algorithm. You can run it with:
ruby bubble_sort.rb | sorthem
Note that compare
isn't actually needed. Only swap
does the job of sorting
the array. compare
is simply a helpful operation for visualization.
Of course, there are more types of operations for more complex algorithms, each associated with semantic color.
You have a variety of examples in the examples directory (WIP).
-
compare: for comparing to indexes
usage:
compare i j
-
swap: for swapping the values of two indexes
usage:
swap i j
-
get: for consulting the value at some index
usage:
get i
-
set: for setting a value at some index
usage:
set i value
where
0 <= value <= max_value
, otherwise panics -
context: makes future index ops relative to this context
usage:
context start end
where
start
andend
fall within the array's bounds -
pop: pops the last context
usage:
pop
panics if there are no contexts to pop
i
and j
must be valid zero-based indexes.
your_sorting_algorithm | sorthem
- Space - pause/resume
- R - restart
- ↑ - speed up
- ↓ - speed down
sorthem
uses SFML for graphics. The instalation
process depends on your OS. See the official documentation.
# Debian based distros
sudo apt update
sudo apt install libsfml-dev
# On MacOS
brew install sfml
There are no official packages for Windows, but you can download the binaries from the official website.
Run the following commands to build sorthem
:
git clone https://github.com/paoloose/sorthem.git
cd sorthem
# On windows, build under WSL
./build.sh
cat examples/test | dist/sorthem