冒泡排序c++可视化程序
时间: 2023-06-28 11:10:06 浏览: 108
以下是冒泡排序的C++可视化程序,使用了Windows API库:
```cpp
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
const int WIDTH = 50; // 控制台宽度
const int HEIGHT = 20; // 控制台高度
const int ARRAY_SIZE = 10; // 数组大小
int arr[ARRAY_SIZE]; // 存储随机数的数组
// 生成随机数
void generateRandomNumbers() {
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = rand() % 100 + 1;
}
}
// 显示数组
void displayArray() {
COORD coord;
coord.X = 0;
coord.Y = 0;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
for (int i = 0; i < ARRAY_SIZE; i++) {
for (int j = 0; j < arr[i]; j++) {
cout << "*";
}
cout << endl;
}
}
// 冒泡排序
void bubbleSort() {
for (int i = 0; i < ARRAY_SIZE - 1; i++) {
for (int j = 0; j < ARRAY_SIZE - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
displayArray();
Sleep(100); // 延迟一段时间,以便观察
}
}
}
}
int main() {
// 初始化控制台
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, WIDTH * 10, HEIGHT * 20, TRUE);
// 初始化随机数数组
generateRandomNumbers();
// 显示随机数数组
displayArray();
// 进行冒泡排序
bubbleSort();
return 0;
}
```
该程序使用了Windows API库控制了控制台的大小,并在控制台中以柱状图的形式显示了随机数数组,并在每次交换数组元素时更新了显示,达到了可视化效果。
阅读全文
相关推荐















