学习C语言有几天了,第一个分享程序:
实现冒泡排序算法原理的简单动画展示,动画原理是最简单的清屏重绘。
环境是WIN764,EGE库,CODEBLOCK 13.12。
欢迎大神指正,能接受轻拍,很基础的东西,也能接受伸手党。
我的CODEBLOCK是英文版,我的英文又很菜,所以没写注释。。。。
直接上代码了:
#include <graphics.h>
#include <stdio.h>
#include <stdlib.h>
//排序算法功能函数
void sortbubble_start();
//将数组画成柱状图,参数为数组指针,要画部分的起始下标和结束下标,颜色选择
void sortbubble_drawarray(int *numarray,int startindex,int endindex,int crgb);
//在窗口底部显示比较次数和遍历次数等
void sortbubble_drawstatus(int len,int traversalnumber,int comparenumber);void sortbubble_drawstatus(int len,int traversalnumber,int comparenumber)
{
char str[5];
int ax=0,ay=680;
setcolor(RED);
setfillcolor(LIGHTGRAY);
setfontbkcolor(LIGHTGRAY);
bar(ax,ay,1200,700);
ax+=10;
outtextxy(ax,ay,"BubbleSort");
ax+=100;
outtextxy(ax,ay,"ArrayLength:");
ax+=100;
sprintf(str,"%d",len);
outtextxy(ax,ay,str);
ax+=40;
outtextxy(ax,ay,"TraversalNumber:");
ax+=120;
sprintf(str,"%d",traversalnumber);
outtextxy(ax,ay,str);
ax+=40;
outtextxy(ax,ay,"CompareNumber:");
ax+=120;
sprintf(str,"%d",comparenumber);
outtextxy(ax,ay,str);
}
void sortbubble_drawarray(int *numarray,int startindex,int endindex,int crgb)
{
int i,ax,ay,ah;
char str[5];
setcolor(LIGHTRED);
switch (crgb)
{
case 0:
setfillcolor(DARKGRAY);
setfontbkcolor(DARKGRAY);
break;
case 1:
setfillcolor(LIGHTGREEN);
setfontbkcolor(LIGHTGREEN);
break;
case 2:
setfillcolor(YELLOW);
setfontbkcolor(YELLOW);
break;
default:
break;
}
for (i=startindex;i<=endindex;i++)
{
ah=3*numarray[i];
ax=100+i*50;
ay=350-ah;
bar(ax,ay,ax+40,ay+ah);
sprintf(str,"%d",numarray[i]);
outtextxy(ax+10,ay+10,str);
}
}
void sortbubble_start()
{
int numarray[20]={10,60,40,30,45,
85,95,54,73,54,
20,88,44,66,77,
18,62,68,24,42};
int len=20,traversalnumber=0,comparenumber=0;
int i,j,k,temp;
sortbubble_drawarray(numarray,0,len-1,0);
sortbubble_drawstatus(len,traversalnumber,comparenumber);
delay_ms(500);
for (i=0;i<len-1;i++)
{
traversalnumber++;
k=0;
for (j=0;j<len-1-i;j++)
{
comparenumber++;
delay_ms(200);
cleardevice();
sortbubble_drawstatus(len,traversalnumber,comparenumber);
sortbubble_drawarray(numarray,0,len-1-i,0);
if (i>0)
sortbubble_drawarray(numarray,len-i,len-1,1);
delay_ms(200);
sortbubble_drawarray(numarray,j,j+1,2);
if (numarray[j]>numarray[j+1])
{
temp=numarray[j];
numarray[j]=numarray[j+1];
numarray[j+1]=temp;
k++;
}
}
if (k==0)
break;
}
cleardevice();
sortbubble_drawstatus(len,traversalnumber,comparenumber);
sortbubble_drawarray(numarray,0,len-1,1);
}
int main()
{
setinitmode(INIT_RENDERMANUAL,320,120);
initgraph(1200,700);
setcaption("PangeEgeUi");
sortbubble_start();
getch();
closegraph();
return 0;
}