Pre-requisite:
Selection SortThe human brain can easily process visuals in spite of long codes to understand the algorithms. In this article,
Selection Sortvisualization has been implemented using
graphics.hlibrary
. As we all know selection sort first finds the minimum element from the unsorted array and swaps it with the first element of the unsorted array in each pass. It becomes difficult to analyze the data manually between two algorithms or vice versa, but plotting graphically it is much easier to understand.
Approach:
- The white line is used to represent the length of number (9 being represented by 9 pixels vertically upwards) while its position represents its index in the array.
- Graphical representation of randomly distributed numbers is shown below.
- Graphically sorting can be shown by first coloring the minimum element from unsorted array as green color.
- Now swap it with the first element of unsorted array and also swap the color for those two number as shown in code by swap_colors() function.
- Here delay() can be increased to see the transition in the graph.
Examples:
Pre-defined Functions Used:
- setcurrentwindow(): A function which is used to set the size of current window.
- setcolor(n): A function which is used to change the color of cursor by changing the value of n.
- delay(n): A function which is used to delay the program by n milliseconds. It is being used for slowing down the transitions speed
- line(x1, y1, x2, y2): A function which is used to draw an line from point (x1, y1) to point (x2, y2). (0, 0) being the left top corner of the screen and bottom right be (n1, n2) where n1, n2 are the width and height of the current window. There are other graphics which can be applied to this line using setcolor().
Below is the program to visualize the
Selection Sort algorithm:
#include <graphics.h>
#include <bits/stdc++.h>
using namespace std;
// Initialize the size
// with the total numbers to sorted
// and the gap to be maintained in graph
vector<int> numbers;
int size = 200;
int gap = 4;
// Function for swapping the lines graphically
void swap_colors(int i, int j, int x, int y)
{
// y is the minimum element,
// first make this number green
// Now, swapping it by making black again
// and then draw the pixels
// for white colour with x value.
setcolor(GREEN);
line(j, size, j, size - y);
delay(500);
setcolor(BLACK);
line(j, size, j, size - y);
setcolor(WHITE);
line(j, size, j, size - x);
// X is the element to be swapped,
// first make this number black
// Now, highlight y with green
// representing the minimum element
// and then draw the pixels
// for white colour with y value.
setcolor(BLACK);
line(i, size, i, size - x);
setcolor(GREEN);
line(i, size, i, size - y);
delay(500);
setcolor(WHITE);
line(i, size, i, size - y);
}
// Selection sort function
void selsort()
{
for (int i = 0; i < size - 1; i++)
{
// Find the minimum element
// in unsorted array
int min_idx = i;
for (int j = i + 1; j < size; j++)
{
if (numbers[j] < numbers[min_idx])
{
min_idx = j;
}
}
// Swap the found minimum element
// with the first element
// delay(500);
swap(&numbers[min_idx], &numbers[i]);
// Function to show transition in swapping
swap_colors(gap * i + 1,
gap * (min_idx) + 1,
numbers[min_idx],
numbers[i]);
}
}
// Driver program
int main()
{
// auto detection of screen size
int gd = DETECT, gm;
int wid1;
// Graph initialization
initgraph(&gd, &gm, NULL);
// setting up window size (gap*size) * (size)
wid1 = initwindow(gap * size + 1, size + 1);
setcurrentwindow(wid1);
// Initializing the array
for (int i = 1; i <= size; i++)
numbers.push_back(i);
// Find a seed and shuffle the array
// to make it random.
// Here different type of array
// can be taken to results
// such as nearly sorted, already sorted,
// reverse sorted to visualize the result
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
shuffle(numbers.begin(), numbers.end(), default_random_engine(seed));
// Initial plot of numbers in graph taking
// the vector position as x-axis and its
// corresponding value will be the height of line.
for (int i = 1; i <= gap * size; i += gap)
{
line(i, size, i, (size - numbers[i / gap]));
}
// Delay the code
delay(200);
// Call sort
selsort();
// Wait for sometime .
delay(5000);
// Close the graph
closegraph();
return 0;
}
import time
import random
import matplotlib.pyplot as plt
# Initialize the size with the total numbers to sorted
# and the gap to be maintained in graph
numbers = []
size = 200
gap = 4
# Function for swapping two numbers
def swap(xp, yp):
return yp, xp
# Selection sort function
def selsort(numbers):
for i in range(size - 1):
# Find the minimum element in unsorted array
min_idx = i
for j in range(i + 1, size):
if numbers[j] < numbers[min_idx]:
min_idx = j
# Swap the found minimum element with the first element
numbers[min_idx], numbers[i] = swap(numbers[min_idx], numbers[i])
# Function to show transition in swapping
plt.bar([i for i in range(len(numbers))], numbers)
plt.show(block=False)
plt.pause(0.1)
plt.clf()
# Driver program
def main():
# Initializing the array
for i in range(1, size + 1):
numbers.append(i)
# Find a seed and shuffle the array to make it random.
# Here different type of array can be taken to results
# such as nearly sorted, already sorted, reverse sorted to visualize the result
random.seed(time.time())
random.shuffle(numbers)
# Initial plot of numbers in graph taking
# the vector position as x-axis and its
# corresponding value will be the height of line.
plt.bar([i for i in range(len(numbers))], numbers)
plt.show(block=False)
plt.pause(0.1)
plt.clf()
# Call sort
selsort(numbers)
for i in range(size):
print(numbers[i], end=" ")
print()
# Wait for sometime
time.sleep(5)
if __name__ == "__main__":
main()
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
Visualization:
- Input Visualization:
- Output Visualization: