#include #include #include #include #include #define ASCII_SPACE 32 #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600 #define SRC_FONT_WIDTH 7 #define SRC_FONT_HEIGHT 9 #define DST_FONT_WIDTH 28 #define DST_FONT_HEIGHT 32 #define ATLAS_WIDTH 18 #define DATASET_SIZE 800 #define STATS_SIZE 80 int main(int argc, char **argv) { srand(time(0)); SDL_Init(SDL_INIT_VIDEO); IMG_Init(IMG_INIT_PNG); SDL_Window *win = SDL_CreateWindow( "Sorting algorithms", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, 0); SDL_Renderer *ren = SDL_CreateRenderer( win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); SDL_Texture *font_atlas = IMG_LoadTexture(ren, "./font.png"); int to_be_sorted[DATASET_SIZE] = {0}; for (int i = 0; i < DATASET_SIZE;i++) { to_be_sorted[i] = i + 1; } for (int i = 0; i < DATASET_SIZE; i++) { int tmp = to_be_sorted[i]; int j = rand() % DATASET_SIZE; to_be_sorted[i] = to_be_sorted[j]; to_be_sorted[j] = tmp; } int sort_index = 0; int sort_index_internal = 0; int comparisons = 0; int swaps = 0; while (1) { SDL_Event e; if (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { break; } } for (int i = 0; i < 10; i++) { if (sort_index < DATASET_SIZE - 1) { if (sort_index_internal >= 0 && to_be_sorted[sort_index_internal] > to_be_sorted[sort_index_internal + 1]) { int tmp = to_be_sorted[sort_index_internal + 1]; to_be_sorted[sort_index_internal + 1] = to_be_sorted[sort_index_internal]; to_be_sorted[sort_index_internal] = tmp; sort_index_internal--; comparisons++; swaps++; } else { sort_index++; sort_index_internal = sort_index; comparisons++; } } } SDL_SetRenderDrawColor(ren, 0, 0, 0, 255); SDL_RenderClear(ren); char stats[STATS_SIZE] = {0}; sprintf(stats, "Comparisons: %d\nSwaps: %d", comparisons, swaps); int line = 0; int col = 0; for (int i = 0; i < STATS_SIZE; i++) { if (stats[i] == '\n') { line++; col = 0; } else { col++; } SDL_Rect src = { (stats[i] - ASCII_SPACE) % ATLAS_WIDTH * SRC_FONT_WIDTH, (stats[i] - ASCII_SPACE) / ATLAS_WIDTH * SRC_FONT_HEIGHT, SRC_FONT_WIDTH, SRC_FONT_HEIGHT }; SDL_Rect dst = { col * DST_FONT_WIDTH, line * DST_FONT_HEIGHT, DST_FONT_WIDTH, DST_FONT_HEIGHT }; SDL_RenderCopy(ren, font_atlas, &src, &dst); } for (int i = 0; i < DATASET_SIZE; i++) { SDL_Rect bar = { i * WINDOW_WIDTH / DATASET_SIZE, WINDOW_HEIGHT, WINDOW_WIDTH / DATASET_SIZE, -to_be_sorted[i] * (int) (0.8 * WINDOW_HEIGHT) / DATASET_SIZE }; if (sort_index_internal == i - 1) { SDL_SetRenderDrawColor(ren, 0, 255, 0, 255); } else if (sort_index == i - 1) { SDL_SetRenderDrawColor(ren, 255, 0, 0, 255); } else { SDL_SetRenderDrawColor(ren, 255, 255, 255, 255); } SDL_RenderFillRect(ren, &bar); } SDL_RenderPresent(ren); } SDL_DestroyWindow(win); SDL_DestroyRenderer(ren); IMG_Quit(); SDL_Quit(); return 0; }