因此,当我使用一个名为Splashkit的游戏制作库创建此排序可视化程序时,(我知道它不是很理想,但是它是我的课程教给我的),我试图显示整个数组并显示每个交换。而是这样做:Video of my bug
当我按照教程来实现此目的时,我并没有理解代码的逻辑。排序本身很好,效果很好,但是矩形的绘制很奇怪,而不是我想要实现的。 I would like to achieve something like this.(无颜色/声音效果)。 代码已更新:
#include "splashkit.h"
#define NUM_VALS 200
void draw_values(const int values[], int size)
{
int x = 0;
int y;
int rect_height;
int rect_width = screen_width() / size;
for (int i = 0; i < size; i++)
{
rect_height = values[i];
y = screen_height() - rect_height;
fill_rectangle(COLOR_RED, x, y, rect_width, rect_height);
draw_rectangle(COLOR_WHITE, x, y, rect_width, rect_height);
x += rect_width;
}
}
void draw_sort(int values[], int size)
{
clear_screen(COLOR_WHITE);
draw_values(values, size);
refresh_screen(60);
}
void swap (int &value1, int &value2)
{
int temp = value1;
value1 = value2;
value2 = temp;
}
/* inspiration/educated from https://www.geeksforgeeks.org/quick-sort/ */
int partition (int values[], int low, int size)
{
int pivot = values[size]; // the pivot value
int i = (low - 1); // currently selected element
// work out if all values have become the pivot value, loop until all have.
for (int j = low; j <= size-1; j++)
{
if (values[j] <= pivot)
{
i++;
swap(values[i], values[j]);
draw_sort(values, size);
}
}
swap(values[i + 1], values[size]);
draw_sort(values, size);
return (i+1);
}
void quick_sort (int values[], int low, int size)
{
if (low < size)
{
// This is the partitioning index for quick sorting
int pi = partition(values, low, size);
// This sorts small partitions at a time then sorts them together.
quick_sort(values, low, (pi - 1));
quick_sort(values, (pi + 1), size);
}
}
void bubble_sort(int values[], int size)
{
for (int j = 0; j < size; j++)
{
for (int i = 0; i < size - 1; i++)
{
if (values[i] > values[i + 1])
{
swap(values[i], values[i + 1]);
draw_sort(values, size);
}
}
}
}
void random_fill_array(int values[], int size)
{
for (int i = 0; i < size; i++)
{
values[i] = rnd(screen_height()) + 1;
}
}
void handle_input(int values[], int size)
{
if (key_typed(R_KEY))
{
random_fill_array(values, size);
}
else if (key_typed(S_KEY))
{
bubble_sort(values, size);
}
else if (key_typed(D_KEY))
{
quick_sort(values, 0, size);
}
}
int main()
{
int values[NUM_VALS];
open_window("Sort Visualiser", 800, 600);
random_fill_array(values, NUM_VALS);
while ( not quit_requested() )
{
process_events();
handle_input(values, NUM_VALS);
draw_sort(values, NUM_VALS);
}
return 0;
}
答案 0 :(得分:5)
在quick_sort
函数中,size
不是列表的大小,而是当前分区的大小,因此,调用{{1}时,您仅绘制当前分区而不是整个列表}。您需要添加具有原始列表大小的其他参数:
draw_sort