Visualización de algoritmos de clasificación: Bubble Sort

El cerebro humano puede procesar imágenes fácilmente a pesar de los códigos largos para comprender los algoritmos. En este artículo, la visualización de clasificación de burbujas se implementó utilizando la biblioteca graphics.h . Como todos sabemos, la ordenación de burbuja intercambia los elementos adyacentes si no están ordenados y, finalmente, el más grande se desplaza hacia el final de la array en cada pasada. A veces, se vuelve difícil analizar los datos manualmente, pero después de trazarlos gráficamente, es mucho más fácil de entender, como se muestra en la figura a continuación.

Bubble Sort

Acercarse:

  • Incluso comparar dos tipos de conjuntos de datos también es difícil con números si el tamaño de la array es grande.
  • La representación gráfica de números distribuidos aleatoriamente y números ordenados inversamente se muestra a continuación.
  • La línea blanca se usa para representar la longitud del número (el 9 está representado por 9 píxeles verticalmente hacia arriba) mientras que su posición representa su índice en la array.
  • La clasificación gráfica se puede mostrar simplemente intercambiando las líneas.
  • A medida que intercambiamos los números en el tipo de burbuja, se puede usar una línea de color diferente para ver el índice actual en la array (aquí, el color verde).
  • Aquí se puede aumentar delay() para ver la transición en el gráfico.

Ejemplos:


Random array

Random array

Reverse sorted array

Reverse sorted array

Funciones predefinidas utilizadas:

  • setcurrentwindow(): una función que se utiliza para establecer el tamaño de la ventana actual.
  • setcolor(n): Una función que se utiliza para cambiar el color del cursor cambiando el valor de n.
  • delay(n): Una función que se utiliza para retrasar el programa por n milisegundos. Se está utilizando para ralentizar la velocidad de las transiciones.
  • línea (x1, y1, x2, y2): una función que se utiliza para dibujar una línea desde el punto (x1, y1) hasta el punto (x2, y2). (0, 0) siendo la esquina superior izquierda de la pantalla y la inferior derecha (n1, n2) donde n1, n2 son el ancho y el alto de la ventana actual. Hay otros gráficos que se pueden aplicar a esta línea usando setcolor() .

A continuación se muestra el programa para visualizar el algoritmo Bubble Sort :

Implementación

// C++ program for visualization of bubble sort
  
#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(int i, int j, int x, int y)
{
    // Swapping the first line with the correct line
    // by making it black again and then draw the pixel
    // for white color.
  
    setcolor(GREEN);
    line(i, size, i, size - x);
    setcolor(BLACK);
    line(i, size, i, size - x); 
    setcolor(WHITE);
    line(i, size, i, size - y); 
  
    // Swapping the first line with the correct line
    // by making it black again and then draw the pixel
    // for white color.
    setcolor(GREEN);
    line(j, size, j, size - y);
    setcolor(BLACK);
    line(j, size, j, size - y);
    setcolor(WHITE);
    line(j, size, j, size - x);
}
  
// Bubble sort function
void bubbleSort()
{
    int temp, i, j;
  
    for (i = 1; i < size; i++) {
        for (j = 0; j < size - i; j++) {
            if (numbers[j] > numbers[j + 1]) {
                temp = numbers[j];
                numbers[j] = numbers[j + 1];
                numbers[j + 1] = temp;
  
                // As we swapped the last two numbers
                // just swap the lines with the values.
                // This is function call
                // for swapping the lines
                swap(gap * j + 1,
                     gap * (j + 1) + 1,
                     numbers[j + 1],
                     numbers[j]);
            }
        }
    }
}
  
// 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
    bubbleSort();
  
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;
  
    // Wait for sometime .
    delay(5000);
  
    // Close the graph
    closegraph();
  
    return 0;
}
Producción:

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


Publicación traducida automáticamente

Artículo escrito por Harshit-Agarwal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *