diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..f67e05a --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,68 @@ +name: build + +on: + push: + branches: ['**'] + tags: ['v*'] + pull_request: + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + name: linux-x64 + - os: windows-latest + name: windows-x64 + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + + - name: Install Linux dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y libx11-dev libxrandr-dev libxcursor-dev libudev-dev libfreetype-dev libgl1-mesa-dev + + - name: Configure + run: cmake -B build -DCMAKE_BUILD_TYPE=Release + + - name: Build + run: cmake --build build --config Release --parallel + + - name: Package + shell: bash + run: | + mkdir pkg + cp build/sort_visualization pkg/ 2>/dev/null || cp build/Release/sort_visualization.exe pkg/ + cp -r Code/font pkg/font + cp README.md LICENSE pkg/ + cd pkg + if [ "${{ runner.os }}" = "Windows" ]; then + 7z a ../sort_visualization-${{ matrix.name }}.zip . + else + zip -r ../sort_visualization-${{ matrix.name }}.zip . + fi + + - uses: actions/upload-artifact@v4 + with: + name: sort_visualization-${{ matrix.name }} + path: sort_visualization-${{ matrix.name }}.zip + + release: + if: startsWith(github.ref, 'refs/tags/v') + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + path: dist + merge-multiple: true + - uses: softprops/action-gh-release@v2 + with: + files: dist/*.zip + generate_release_notes: true diff --git a/CMakeLists.txt b/CMakeLists.txt index 64889fb..6944249 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,16 +1,38 @@ -cmake_minimum_required(VERSION 3.10) +cmake_minimum_required(VERSION 3.16) +# Static MSVC runtime (/MT), same as SFML_USE_STATIC_STD_LIBS. Set before project(). +cmake_policy(SET CMP0091 NEW) +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") project(sort_visualization CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release) +endif() -find_package(SFML 2 REQUIRED COMPONENTS graphics window system) +# SFML 2.6.2 is downloaded and built as a static library. No manual install. +include(FetchContent) +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(SFML_BUILD_AUDIO OFF CACHE BOOL "" FORCE) +set(SFML_BUILD_NETWORK OFF CACHE BOOL "" FORCE) +set(SFML_USE_STATIC_STD_LIBS ON CACHE BOOL "" FORCE) +set(CMAKE_POLICY_VERSION_MINIMUM 3.5) # SFML 2.6 declares an old minimum version +FetchContent_Declare(SFML + URL https://github.com/SFML/SFML/archive/refs/tags/2.6.2.tar.gz + DOWNLOAD_EXTRACT_TIMESTAMP ON) +FetchContent_MakeAvailable(SFML) + +# Embed the font in the executable, so it works from any working directory. +file(READ ${CMAKE_SOURCE_DIR}/Code/font/Ruda-Medium.ttf FONT_HEX HEX) +string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," FONT_ARRAY "${FONT_HEX}") +file(WRITE ${CMAKE_BINARY_DIR}/font_data.cpp + "extern const unsigned char font_data[] = {${FONT_ARRAY}};\n" + "extern const unsigned long font_data_size = sizeof(font_data);\n") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${CMAKE_SOURCE_DIR}/Code/font/Ruda-Medium.ttf) file(GLOB SOURCES ${CMAKE_SOURCE_DIR}/Code/*.cpp) -add_executable(sort_visualization ${SOURCES}) +add_executable(sort_visualization ${SOURCES} ${CMAKE_BINARY_DIR}/font_data.cpp) target_link_libraries(sort_visualization PRIVATE sfml-graphics sfml-window sfml-system) - -# The program loads "font/Ruda-Medium.ttf" relative to the working directory. -add_custom_command(TARGET sort_visualization POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_directory - ${CMAKE_SOURCE_DIR}/Code/font $/font) +if(WIN32) + target_compile_definitions(sort_visualization PRIVATE SFML_STATIC) +endif() diff --git a/Code/AnotherFunc.cpp b/Code/AnotherFunc.cpp index 0f90ceb..c751575 100644 --- a/Code/AnotherFunc.cpp +++ b/Code/AnotherFunc.cpp @@ -75,9 +75,13 @@ sf::Text get_text(std::string text_line, int size, int x, int y, int screen_widt return text; } +// The font bytes are compiled in (see CMakeLists.txt), so no file lookup is needed. +extern const unsigned char font_data[]; +extern const unsigned long font_data_size; + sf::Font get_font() { sf::Font font = sf::Font{}; - if (!font.loadFromFile("font/Ruda-Medium.ttf")) + if (!font.loadFromMemory(font_data, font_data_size)) { sf::err() << "Couldn't load font\n"; } diff --git a/Code/ArrayDrawer.cpp b/Code/ArrayDrawer.cpp index 0b0308f..b7bfa2f 100644 --- a/Code/ArrayDrawer.cpp +++ b/Code/ArrayDrawer.cpp @@ -16,7 +16,7 @@ ArrayDrawer::ArrayDrawer(int screen_width, int screen_height, int vector_one_ite sub_text_size = screen_height / 50; } -void ArrayDrawer::draw_colums(sf::RenderWindow& window, std::vector array, int main_column, int sub_column) { +void ArrayDrawer::draw_colums(sf::RenderTarget& window, std::vector array, int main_column, int sub_column) { for (int i = 0; i < array.size(); i++) { if (i == main_column) { window.draw(get_rectangle(i * vector_one_item_size, 0, 1 * vector_one_item_size, array[i], main_column_color)); @@ -30,7 +30,7 @@ void ArrayDrawer::draw_colums(sf::RenderWindow& window, std::vector array, } } -void ArrayDrawer::draw_points(sf::RenderWindow& window, std::vector array, int main_column, int sub_column) { +void ArrayDrawer::draw_points(sf::RenderTarget& window, std::vector array, int main_column, int sub_column) { for (int i = 0; i < array.size(); i++) { if (i == main_column) { window.draw(get_circle(vector_one_item_size * 2, i * vector_one_item_size - vector_one_item_size, screen_height - array[i] - vector_one_item_size, main_column_color)); @@ -44,7 +44,7 @@ void ArrayDrawer::draw_points(sf::RenderWindow& window, std::vector array, } } -void ArrayDrawer::draw_circumference(sf::RenderWindow& window, std::vector array, int main_column, int sub_column) { +void ArrayDrawer::draw_circumference(sf::RenderTarget& window, std::vector array, int main_column, int sub_column) { float radius_for_circle_of_dots = screen_height / 3; float radius_for_dots = screen_height / array.size(); @@ -92,7 +92,7 @@ void ArrayDrawer::draw_circumference(sf::RenderWindow& window, std::vector } } -void ArrayDrawer::draw_spiral(sf::RenderWindow& window, std::vector array, int main_column, int sub_column) { +void ArrayDrawer::draw_spiral(sf::RenderTarget& window, std::vector array, int main_column, int sub_column) { float color_for_element = 360.0 / screen_height; float angel_per_element = 360.0 / array.size() * pi / 180.0; @@ -128,7 +128,7 @@ void ArrayDrawer::draw_spiral(sf::RenderWindow& window, std::vector array, } } -void ArrayDrawer::draw_pyramid(sf::RenderWindow& window, std::vector array, int main_column, int sub_column) { +void ArrayDrawer::draw_pyramid(sf::RenderTarget& window, std::vector array, int main_column, int sub_column) { float height_of_pyramid = screen_height / 2.0; float Ox = screen_width / 2.0; @@ -155,7 +155,7 @@ void ArrayDrawer::draw_pyramid(sf::RenderWindow& window, std::vector array, } } -void ArrayDrawer::draw_array(sf::RenderWindow& window, std::vector array, int main_column, int sub_column, bool reset_screen) { +void ArrayDrawer::draw_array(sf::RenderTarget& window, std::vector array, int main_column, int sub_column, bool reset_screen) { if (reset_screen) { window.clear(background_color); @@ -191,7 +191,11 @@ void ArrayDrawer::draw_array(sf::RenderWindow& window, std::vector array, i window.draw(get_text(speed_string, sub_text_size, screen_width / 2, screen_height * 0.82, screen_width, screen_height, column_color, background_color, font)); } - if (reset_screen) window.display(); + if (reset_screen) { + // The target is the window, or an offscreen texture in record mode. + if (auto* w = dynamic_cast(&window)) w->display(); + else if (auto* t = dynamic_cast(&window)) t->display(); + } } void ArrayDrawer::set_sort_name(std::string sort_name) { diff --git a/Code/ArrayDrawer.hpp b/Code/ArrayDrawer.hpp index 638dd8d..e996d14 100644 --- a/Code/ArrayDrawer.hpp +++ b/Code/ArrayDrawer.hpp @@ -21,13 +21,13 @@ class ArrayDrawer { public: ArrayDrawer(int screen_width, int screen_height, int vector_one_item_size, int max_speed); - void draw_colums(sf::RenderWindow& window, std::vector array, int main_column, int sub_column); - void draw_points(sf::RenderWindow& window, std::vector array, int main_column, int sub_column); - void draw_circumference(sf::RenderWindow& window, std::vector array, int main_column, int sub_column); - void draw_spiral(sf::RenderWindow& window, std::vector array, int main_column, int sub_column); - void draw_pyramid(sf::RenderWindow& window, std::vector array, int main_column, int sub_column); + void draw_colums(sf::RenderTarget& window, std::vector array, int main_column, int sub_column); + void draw_points(sf::RenderTarget& window, std::vector array, int main_column, int sub_column); + void draw_circumference(sf::RenderTarget& window, std::vector array, int main_column, int sub_column); + void draw_spiral(sf::RenderTarget& window, std::vector array, int main_column, int sub_column); + void draw_pyramid(sf::RenderTarget& window, std::vector array, int main_column, int sub_column); - void draw_array( sf::RenderWindow& window, std::vector array, int main_column, int sub_column, bool reset_screen); + void draw_array( sf::RenderTarget& window, std::vector array, int main_column, int sub_column, bool reset_screen); void set_sort_name(std::string sort_name); void set_choice(int choice); void set_speed(int speed); diff --git a/Code/Main.cpp b/Code/Main.cpp index 4b119c8..dc1fa76 100644 --- a/Code/Main.cpp +++ b/Code/Main.cpp @@ -1,5 +1,10 @@ #include "Menu.hpp" #include "ShuffleAlgorithms.hpp" +#include +#include +#include +#include +#include // ---------------- const values int main(); @@ -15,13 +20,19 @@ int faster; int const max_speed = vector_lenght; bool draw = true; -sf::RenderWindow window(sf::VideoMode(screen_width, screen_height), "Sort visualization"); +// SFML is a static library. Objects that use SFML (window, fonts, textures) must not be +// globals: they would be built before SFML is ready and destroyed after it is gone. +// So they are created on first use, inside functions. +// The window is created in main(). Record mode draws offscreen and never opens it. +sf::RenderWindow& get_window() { static sf::RenderWindow w; return w; } +#define window get_window() sf::Time long_sleep = sf::seconds(2); sf::Time short_sleep = sf::seconds(0.1); -ArrayDrawer drawer(screen_width, screen_height, vector_one_item_size, max_speed); -Menu menu(screen_width, screen_height); +ArrayDrawer& get_drawer() { static ArrayDrawer d(screen_width, screen_height, vector_one_item_size, max_speed); return d; } +Menu& get_menu() { static Menu m(screen_width, screen_height); return m; } +#define menu get_menu() bool key_press_for_visualizer(int draw) { sf::Event event; @@ -31,7 +42,7 @@ bool key_press_for_visualizer(int draw) { { if (event.key.code == sf::Keyboard::Escape) { - drawer.set_sort_name(""); + get_drawer().set_sort_name(""); main(); exit(1); @@ -43,7 +54,7 @@ bool key_press_for_visualizer(int draw) { } else if (faster < max_speed) { faster += faster_const; } - drawer.set_speed(faster); + get_drawer().set_speed(faster); return false; } if (event.key.code == sf::Keyboard::Left || event.key.code == sf::Keyboard::A) @@ -51,7 +62,7 @@ bool key_press_for_visualizer(int draw) { if (faster != faster_const) { faster = faster_const; } - drawer.set_speed(1); + get_drawer().set_speed(1); return true; } } @@ -59,10 +70,37 @@ bool key_press_for_visualizer(int draw) { return draw * 1; } +// ---------------- record mode (see "Record" in README.md) +// SORTVIS_RECORD= turns it on. The program then draws into an +// offscreen texture, saves frames as /f000000.png ..., and exits. +struct Recorder { + bool on = false; + bool counting = false; // dry run: count steps, draw nothing + long steps = 0, every = 1; // save a frame every `every` steps + int frame = 0; + std::string dir; + std::unique_ptr canvas; // made in record(): a global texture would need GL before SFML is ready + ArrayDrawer drawer{ screen_width, screen_height, int(vector_one_item_size), 0 }; // 0: no speed line +}; +Recorder& get_rec() { static Recorder r; return r; } +#define rec get_rec() + +void record_frame(const std::vector& array, int first_column, int second_column) { + rec.drawer.draw_array(*rec.canvas, array, first_column, second_column, 1); + char path[1024]; + std::snprintf(path, sizeof path, "%s/f%06d.png", rec.dir.c_str(), rec.frame++); + rec.canvas->getTexture().copyToImage().saveToFile(path); +} + void drawing(std::vector *array, int i, int first_column, int second_column) { + if (rec.on) { + if (!rec.counting && rec.steps % rec.every == 0) record_frame(*array, first_column, second_column); + rec.steps++; + return; + } draw = key_press_for_visualizer(draw); if (draw || i % faster == 0) { - drawer.draw_array(window, *array, first_column, second_column, 1); + get_drawer().draw_array(window, *array, first_column, second_column, 1); } } @@ -79,41 +117,115 @@ void sort_visualization(){ draw = true; faster = faster_const; - drawer.set_speed(1); + get_drawer().set_speed(1); for (int i = 0; i < sort_order.size(); i++) { - drawer.draw_array(window, array, -1, -1, 1); + get_drawer().draw_array(window, array, -1, -1, 1); sf::sleep(long_sleep); - drawer.set_sort_name("Shuffle"); + get_drawer().set_sort_name("Shuffle"); start_shuffle(&array, shuffle_order[i]); - drawer.draw_array(window, array, -1, -1, 1); + get_drawer().draw_array(window, array, -1, -1, 1); sf::sleep(long_sleep); draw = true; faster = faster_const; - drawer.set_speed(1); + get_drawer().set_speed(1); - drawer.set_sort_name(sort_order[i] + " sort"); + get_drawer().set_sort_name(sort_order[i] + " sort"); start_right_sort(&array, sort_order[i]); - drawer.draw_array(window, array, -1, -1, 1); + get_drawer().draw_array(window, array, -1, -1, 1); sf::sleep(long_sleep); } sf::sleep(long_sleep); } +int env_int(const char* name, int fallback) { + const char* v = std::getenv(name); + return v ? std::atoi(v) : fallback; +} + +// Runs `step` once without drawing to count its steps, then sets the +// frame step so that the real run saves about `frames` frames. +template +void plan_frames(std::vector array, int frames, F step) { + rec.counting = true; + rec.steps = 0; + step(&array); + rec.counting = false; + rec.every = rec.steps / frames > 1 ? rec.steps / frames : 1; + rec.steps = 0; +} + +// One clip: sorted array -> shuffle -> sort -> sorted array. +int record() { + std::vector layouts = { "columns", "points", "circle", "spiral", "pyramid" }; + const char* layout = std::getenv("SORTVIS_LAYOUT"); + int choice = 1; + for (int i = 0; layout && i < layouts.size(); i++) if (layouts[i] == layout) choice = i + 1; + + const char* sort_env = std::getenv("SORTVIS_SORT"); + std::string sort = sort_env ? sort_env : "Quick"; + std::vector sorts = get_sorts_table_origin(); + if (std::find(sorts.begin(), sorts.end(), sort) == sorts.end()) { + std::cerr << "Unknown SORTVIS_SORT: " << sort << "\n"; + return 1; + } + int frames = env_int("SORTVIS_FRAMES", 300); + srand(env_int("SORTVIS_SEED", 1)); + + rec.canvas.reset(new sf::RenderTexture); + if (!rec.canvas->create(screen_width, screen_height)) return 1; + menu.set_theme(env_int("SORTVIS_THEME", 0)); + std::vector colors = menu.get_colors(); + rec.drawer.set_colors(colors[0], colors[2], colors[3], colors[4]); + rec.drawer.set_choice(choice); + + std::vector array = menu.get_array(); + record_frame(array, -1, -1); + + unsigned seed = rand(); + auto shuffle = [](std::vector* a) { random_shuffle_vector(a, true); }; + srand(seed); plan_frames(array, frames / 6, shuffle); + srand(seed); rec.drawer.set_sort_name("Shuffle"); shuffle(&array); + record_frame(array, -1, -1); + + int sort_start = rec.frame; + auto sorter = [&sort](std::vector* a) { start_right_sort(a, sort); }; + seed = rand(); + srand(seed); plan_frames(array, frames, sorter); + srand(seed); rec.drawer.set_sort_name(sort + " sort"); sorter(&array); + record_frame(array, -1, -1); + + std::cout << rec.frame << " frames, sort starts at frame " << sort_start + << ", 1 sort frame every " << rec.every << " steps\n"; + return 0; +} + int main() { + static bool started = false; + if (!started) { + started = true; + const char* dir = std::getenv("SORTVIS_RECORD"); + if (dir) { + rec.on = true; + rec.dir = dir; + return record(); + } + window.create(sf::VideoMode(screen_width, screen_height), "Sort visualization"); + } + srand(time(NULL)); while (true) { - drawer.set_choice(menu.start(window)); + get_drawer().set_choice(menu.start(window)); std::vector colors = menu.get_colors(); - drawer.set_colors(colors[0], colors[2], colors[3], colors[4]); + get_drawer().set_colors(colors[0], colors[2], colors[3], colors[4]); sort_visualization(); } diff --git a/Code/Menu.cpp b/Code/Menu.cpp index e17cfef..9652d71 100644 --- a/Code/Menu.cpp +++ b/Code/Menu.cpp @@ -342,6 +342,10 @@ int Menu::start(sf::RenderWindow& window) { std::vector Menu::get_colors() { return themes[themes_choice]; } +void Menu::set_theme(int theme) { + themes_choice = theme; + check_if_number_is_less_or_greater(themes_choice, 0, themes.size() - 1); +} std::vector Menu::get_array() { return array; } diff --git a/Code/Menu.hpp b/Code/Menu.hpp index 73436c4..78b5a7c 100644 --- a/Code/Menu.hpp +++ b/Code/Menu.hpp @@ -58,6 +58,7 @@ class Menu { int start(sf::RenderWindow& window); std::vector get_colors(); + void set_theme(int theme); std::vector get_array(); std::vector get_sort_table(); }; diff --git a/README.md b/README.md index ad65373..41b3aea 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,60 @@ # sort_visualization -A sorting algorithm visualizer written in C++ with SFML. +A sorting algorithm visualizer in C++ with SFML: 16 algorithms, 5 ways to draw the array. - +![Five short clips from the program: Quick sort as columns, Merge sort as points, Heap sort on a circle, Radix sort as a spiral, and Shell sort as a pyramid. Each clip shows the sorted array, a shuffle, and the sort.](docs/hero.gif) -## What +All images on this page are frames saved by the program itself (see [Record](#record)). -- 16 sorting algorithms. +## Run + +### Download + +Get the zip for your system from the [Releases page](https://github.com/ilyaeis/sort_visualization/releases/latest) (`linux-x64` or `windows-x64`), unzip it and start `sort_visualization` (`sort_visualization.exe` on Windows). The font is built into the program, and SFML is linked in, so nothing else needs to be installed. On Linux you need a desktop session with OpenGL. + +### Build from source + +You need a C++17 compiler and CMake 3.16 or newer. CMake downloads and builds SFML 2.6.2 for you (static), so you do not install SFML. + +```sh +git clone https://github.com/ilyaeis/sort_visualization.git +cd sort_visualization +cmake -B build && cmake --build build +./build/sort_visualization # Windows: build\Debug\sort_visualization.exe or build\Release\... +``` + +On Debian or Ubuntu, install the build tools and the system libraries that SFML needs once: + +```sh +sudo apt install build-essential cmake git libx11-dev libxrandr-dev libxcursor-dev libudev-dev libfreetype-dev libgl1-mesa-dev +``` + +On Windows, use Visual Studio (with the C++ workload) or MinGW; the same two `cmake` commands work. For a faster program on Windows with Visual Studio, add `--config Release` to the build command. + +You can run the program from any folder. + +## What it does + +- 16 sorting algorithms on an array of 500 values. - 3 ways to fill the array before sorting: ascending, descending, random. The program also shuffles the array between runs. -- 5 layouts: columns, points, circumference, spiral, pyramid. +- 5 layouts: columns, points, circle (the menu calls it "Circumference"), spiral, pyramid. - 5 colour themes. - An option to set the order in which the sorting algorithms run. +- The two values that the algorithm touches in a step get a highlight colour. + +![The five layouts in the middle of a sort, side by side: columns, points, circle, spiral and pyramid.](docs/layouts.png) + +## How it works + +1. **Menu.** You pick a layout, and in the settings a theme, the fill order and the order of the algorithms. +2. **Fill.** The menu fills the array (ascending by default). +3. **Shuffle.** Before each algorithm, a shuffle mixes the array. The shuffle is drawn too. +4. **Sort.** The algorithms run one after another. Each algorithm calls `drawing()` once per step (a compare, a swap or a write) with the two indexes it works on. +5. **Draw.** `drawing()` asks `ArrayDrawer` to draw the array. The drawer maps each value onto the chosen layout: a column height, a point height, a position on a circle, a spiral radius, or an ellipse size in the pyramid. In the circle, spiral and pyramid layouts the colour also comes from the value. + +At normal speed every step is drawn. When you speed up, only every n-th step is drawn. + +Code: `Code/Main.cpp` (main loop, `drawing()`, record mode), `Code/Menu.cpp`, `Code/SortAlgorithms.cpp`, `Code/ShuffleAlgorithms.cpp`, `Code/ArrayDrawer.cpp` (layouts). ## Controls @@ -25,33 +69,148 @@ A sorting algorithm visualizer written in C++ with SFML. Known detail: Esc during a sort restarts the menu with a recursive call to `main()`. This is kept as is. -## Build +## Record + +Record mode saves one run as PNG frames. It skips the menu and does not open a window: it draws into an offscreen texture. It runs one clip (sorted array, shuffle, sort, sorted array) and exits. Without `SORTVIS_RECORD` the program works as before. + +| Variable | Meaning | Default | +| --- | --- | --- | +| `SORTVIS_RECORD` | Folder for the frames (`f000000.png`, ...). Turns record mode on. The folder must exist. | off | +| `SORTVIS_LAYOUT` | `columns`, `points`, `circle`, `spiral` or `pyramid` | `columns` | +| `SORTVIS_SORT` | Algorithm name as in the menu table, for example `Quick`, `Odd-Even` | `Quick` | +| `SORTVIS_FRAMES` | About how many frames the sort gets. The shuffle gets 1/6 of this. | `300` | +| `SORTVIS_THEME` | Colour theme, 0 to 4 | `0` | +| `SORTVIS_SEED` | Random seed for the shuffle | `1` | + +The program first runs the algorithm once without drawing to count its steps. Then it saves one frame every (steps / frames) steps. So a slow algorithm and a fast one both give about the same number of frames. + +```sh +mkdir -p frames +SORTVIS_RECORD=frames SORTVIS_LAYOUT=spiral SORTVIS_SORT=Radix SORTVIS_FRAMES=60 ./build/sort_visualization +``` -You need a C++17 compiler, CMake 3.10 or newer, and SFML 2.x (graphics, window, system). +SFML still needs a graphics context, so on Linux it needs a running X or Wayland session, but no window appears. -Linux (Debian or Ubuntu): +To make a GIF from the frames (this is how `docs/hero.gif` was made, one clip per layout, joined): ```sh -sudo apt install build-essential cmake libsfml-dev -cmake -B build -cmake --build build -cd build && ./sort_visualization +ffmpeg -framerate 15 -i frames/f%06d.png \ + -vf "scale=480:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=64:stats_mode=diff[p];[b][p]paletteuse=dither=none:diff_mode=rectangle" \ + clip.gif ``` -The program loads `font/Ruda-Medium.ttf` from the working directory. CMake copies the font next to the executable, so run the program from `build/`. +## Algorithms + +Each strip shows, from left to right: the shuffled array, the sort at about 25 %, 50 % and 75 % of its steps, and the sorted array. Columns layout, theme 0, seed 1. + +### Bubble + +Swaps neighbours that are in the wrong order. The large values move to the end first. + +![Bubble sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/bubble.png) + +### Insertion + +Takes the next value and moves it left into the sorted part. + +![Insertion sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/insertion.png) + +### Gnome + +Like insertion sort, but it moves one swap at a time, forward and back. + +![Gnome sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/gnome.png) + +### Selection + +Finds the smallest value in the unsorted part and puts it at the front. -Windows: install SFML 2.x, point CMake to it with `-DSFML_DIR=/lib/cmake/SFML`, and build with Visual Studio or MinGW. Put the SFML DLLs next to the executable. This repository no longer contains pre-built binaries or DLLs. +![Selection sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/selection.png) + +### Odd-Even + +Compares pairs at odd positions, then pairs at even positions, until no swap happens. + +![Odd-Even sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/odd-even.png) + +### Count + +Counts how often each value occurs, then writes the values back in order. + +![Count sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/count.png) + +### Pigeonhole + +Puts each value into its own hole, then reads the holes in order. + +![Pigeonhole sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/pigeonhole.png) + +### Radix + +Sorts by the last digit, then the next digit, and so on (base 10). + +![Radix sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/radix.png) + +### Comb + +Bubble sort with a gap that gets smaller each pass. + +![Comb sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/comb.png) + +### Shell + +Insertion sort on values a gap apart, with smaller gaps each pass. + +![Shell sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/shell.png) + +### Merge + +Sorts both halves, then merges them. + +![Merge sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/merge.png) + +### Quick + +Splits the array round a pivot, then sorts each part. + +![Quick sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/quick.png) + +### Pancake + +Flips the front of the array to bring the largest value to its place. + +![Pancake sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/pancake.png) + +### Cocktail + +Bubble sort in both directions. + +![Cocktail sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/cocktail.png) + +### Heap + +Builds a max-heap, then moves the top to the end, again and again. + +![Heap sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/heap.png) + +### Stooge + +Sorts the first 2/3, the last 2/3, then the first 2/3 again. It is very slow. + +![Stooge sort in the columns layout: shuffled array, then three steps of the sort, then the sorted array.](docs/algorithms/stooge.png) ## Stack - C++17 -- SFML 2.5 or newer (tested with 2.6.2) +- SFML 2.6.2 (downloaded by CMake, linked static) - CMake ## Status -Finished in 2022. No new features are planned. +A school project, finished in 2022. No new features are planned. In 2026 a record mode and this README with images were added. ## License MIT, see `LICENSE`. The font `Code/font/Ruda-Medium.ttf` is Ruda under the SIL Open Font License 1.1, see `Code/font/OFL.txt`. + +Part of my portfolio: https://ilyaeis.github.io/?go=sorting diff --git a/docs/algorithms/bubble.png b/docs/algorithms/bubble.png new file mode 100644 index 0000000..1976af4 Binary files /dev/null and b/docs/algorithms/bubble.png differ diff --git a/docs/algorithms/cocktail.png b/docs/algorithms/cocktail.png new file mode 100644 index 0000000..76cd7d8 Binary files /dev/null and b/docs/algorithms/cocktail.png differ diff --git a/docs/algorithms/comb.png b/docs/algorithms/comb.png new file mode 100644 index 0000000..0ae55a8 Binary files /dev/null and b/docs/algorithms/comb.png differ diff --git a/docs/algorithms/count.png b/docs/algorithms/count.png new file mode 100644 index 0000000..1a8ea92 Binary files /dev/null and b/docs/algorithms/count.png differ diff --git a/docs/algorithms/gnome.png b/docs/algorithms/gnome.png new file mode 100644 index 0000000..f8615e6 Binary files /dev/null and b/docs/algorithms/gnome.png differ diff --git a/docs/algorithms/heap.png b/docs/algorithms/heap.png new file mode 100644 index 0000000..5e4d483 Binary files /dev/null and b/docs/algorithms/heap.png differ diff --git a/docs/algorithms/insertion.png b/docs/algorithms/insertion.png new file mode 100644 index 0000000..4360259 Binary files /dev/null and b/docs/algorithms/insertion.png differ diff --git a/docs/algorithms/merge.png b/docs/algorithms/merge.png new file mode 100644 index 0000000..0208115 Binary files /dev/null and b/docs/algorithms/merge.png differ diff --git a/docs/algorithms/odd-even.png b/docs/algorithms/odd-even.png new file mode 100644 index 0000000..59d3826 Binary files /dev/null and b/docs/algorithms/odd-even.png differ diff --git a/docs/algorithms/pancake.png b/docs/algorithms/pancake.png new file mode 100644 index 0000000..e5d0f48 Binary files /dev/null and b/docs/algorithms/pancake.png differ diff --git a/docs/algorithms/pigeonhole.png b/docs/algorithms/pigeonhole.png new file mode 100644 index 0000000..d2ea9c9 Binary files /dev/null and b/docs/algorithms/pigeonhole.png differ diff --git a/docs/algorithms/quick.png b/docs/algorithms/quick.png new file mode 100644 index 0000000..d70378c Binary files /dev/null and b/docs/algorithms/quick.png differ diff --git a/docs/algorithms/radix.png b/docs/algorithms/radix.png new file mode 100644 index 0000000..1015aaa Binary files /dev/null and b/docs/algorithms/radix.png differ diff --git a/docs/algorithms/selection.png b/docs/algorithms/selection.png new file mode 100644 index 0000000..2dede8c Binary files /dev/null and b/docs/algorithms/selection.png differ diff --git a/docs/algorithms/shell.png b/docs/algorithms/shell.png new file mode 100644 index 0000000..dab32f3 Binary files /dev/null and b/docs/algorithms/shell.png differ diff --git a/docs/algorithms/stooge.png b/docs/algorithms/stooge.png new file mode 100644 index 0000000..fe6368a Binary files /dev/null and b/docs/algorithms/stooge.png differ diff --git a/docs/hero.gif b/docs/hero.gif new file mode 100644 index 0000000..97a9206 Binary files /dev/null and b/docs/hero.gif differ diff --git a/docs/layouts.png b/docs/layouts.png new file mode 100644 index 0000000..c9fd2a2 Binary files /dev/null and b/docs/layouts.png differ