使用 easyX 库实现顺序表插入操作的可视化
引言
在数据结构的学习过程中,理解顺序表的基本操作是非常重要的。本文将介绍如何使用 easyX 库来可视化顺序表的插入操作。通过动态展示插入过程,我们可以更直观地了解顺序表的工作原理。
可视化顺序表插入操作
源码展示:
#undef UNICODE
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "graphics.h"
#include<mmsystem.h>
#pragma comment(lib,"winmm.lib")
#define MAX_SIZE 10
#define RECT_WIDTH 100
#define RECT_HEIGHT 50
#define START_X 10
#define START_Y 150
void drawArray(int arr[], int size, int position);
void insertElement(int arr[], int* size, int value, int position, int tempArr[]);
int main() {
int arr[MAX_SIZE] = { 10,20,40,50,60,70,80,90,100 };
int tempArr[MAX_SIZE];
int size = 9;
int value = 30;
int position = -1;
mciSendString("open music/music.mp3", NULL, 0, NULL);
mciSendString("play music/music.mp3", NULL, 0, NULL);
for (int i = 0; i < size; i++) {
if (arr[i] > value) {
position = i;
break;
}
}
initgraph(1024, 500);
drawArray(arr, size, position);
for (int i = 0; i <= size; i++) {
tempArr[i] = arr[i];
}
tempArr[size] = value;
BeginBatchDraw();
insertElement(tempArr, &size, value, position, tempArr);
EndBatchDraw();
_getch();
closegraph();
return 0;
}
void drawArray(int arr[], int size, int position) {
cleardevice();
setbkcolor(WHITE);
setlinecolor(BLACK);
for (int i = 0; i <= size; i++) {
if (i < MAX_SIZE) {
bar(i * RECT_WIDTH + START_X, START_Y, i * RECT_WIDTH + START_X + RECT_WIDTH, START_Y + RECT_HEIGHT);
line(i * RECT_WIDTH + START_X, START_Y, i * RECT_WIDTH + START_X + RECT_WIDTH, START_Y);
line(i * RECT_WIDTH + START_X + RECT_WIDTH, START_Y, i * RECT_WIDTH + START_X + RECT_WIDTH, START_Y + RECT_HEIGHT);
line(i * RECT_WIDTH + START_X, START_Y + RECT_HEIGHT, i * RECT_WIDTH + START_X + RECT_WIDTH, START_Y + RECT_HEIGHT);
line(i * RECT_WIDTH + START_X, START_Y, i * RECT_WIDTH + START_X, START_Y + RECT_HEIGHT);
char strNum[16];
sprintf_s(strNum, "%d", arr[i]);
int textX = i * RECT_WIDTH + START_X + RECT_WIDTH / 2 - 20;
int textY = START_Y + RECT_HEIGHT / 2 - 20;
if (arr[i] == 30) {
settextcolor(RED);
}
else {
settextcolor(BLACK);
}
outtextxy(textX, textY, strNum);
}
}
int titleX = 300;
int titleY = 20;
settextcolor(RED);
settextstyle(45, 0, "楷体");
outtextxy(titleX, titleY, "可视化顺序表插入操作");
}
void insertElement(int arr[], int* size, int value, int position, int tempArr[]) {
if (*size == MAX_SIZE || position < 0)return;
int originalValues[10];
for (int i = *size; i > position; i--) {
originalValues[i] = arr[i - 1];
arr[i] = value;
drawArray(arr, *size, position);
getchar();
if (i == 9)
outtextxy(150, 250, "我们将实现将30有序表插入正确的位置");
else {
outtextxy(160, 250, "每次判断是否大于前一个位置的值");
outtextxy(25, 325, "如果大于,往前移,L->data[j+1] = L->data[j]");
outtextxy(150, 400, "否则,为待插入的位置,退出循环");
}
FlushBatchDraw();
arr[i] = originalValues[i];
}
arr[position] = value;
(*size)++;
drawArray(arr, *size, position);
getchar();
outtextxy(125, 250, "30>20,该位置是待插入的位置,结束循环");
outtextxy(280, 350, "顺序插入元素操作成功");
}