1说明: 1。1冒泡排序: 1。1。1原理:比较两个相邻的元素,将值大的元素交换至右端。 1。1。2来源:由来是因为越大的元素会经由交换慢慢浮到数列的顶端,故得名。 1。1。3是一种最简单直观的排序算法之一。 1。2冒泡排序可视化: 1。2。1BubbleSortVisualizer。 1。2。2更能直观了解这种排序。 1。2。3通过多种方法实现,理解该算法,同时复习python。 1。2。4python法,采用:matplotlib法、pygame法、turtle法(2d3d)、opencv法。 1。2。5代码来源网络,来源已注明,仅供学习,感谢网友,适合收藏。 具体代码和讲解 2python法: 2。1matplotlib法 2。1。1效果图: 2。1。2代码来源:https:blog。csdn。netm1090760001articledetails103217052 2。1。3代码一:frommatplotlibimportpyplotaspltimportrandomLISTSIZE1010个组barPAUSETIME4LISTSIZE冒泡算法defbubblesort(nums):foriinrange(len(nums)1):forjinrange(len(nums)i1):ifnums〔j〕nums〔j1〕:nums〔j〕,nums〔j1〕nums〔j1〕,nums〔j〕plt。cla()清除内容plt。bar(range(len(nums)),nums,aligncenter)plt。bar(j,nums〔j〕,colorr,aligncenter)plt。bar(j1,nums〔j1〕,colorr,aligncenter)plt。pause(PAUSETIME)plt。show()ifnamemain:nums〔〕foriinrange(LISTSIZE):nums。append(random。randint(0,1000))随机生成bubblesort(nums)print(nums) 2。2turtle法: 2。2。12dturtle法: 2。2。1。1来源:https:blog。csdn。netavskyaarticledetails82958907 2。2。1。2效果图: 2。2。1。3代码二:fromturtleimportfromrandomimportrandintfromtimeimportsleepclassColumn(Turtle):definit(self,x):Turtle。init(self,shapesquare)self。up()抬笔rrandint(0,255)grandint(0,255)brandint(0,255)self。fillcolor(r,g,b)self。scalerandint(1,38)20self。scale为柱子高度self。setx(x)self。halfself。screen。windowheight()2屏幕的半高self。shapesize(self。scale,1)相对于自身坐标系前进的垂直方向放大self。sety(0self。half10self。scale30)ifnamemain:width,height800,800screenScreen()screen。colormode(255)screen。setup(width,height)screen。title(冒泡排序动态演示)screen。delay(0)xcors〔xforxinrange(40width2,width220,40)〕columns〔Column(x)forxinxcors〕生成所有柱子lengthlen(columns)whileTrue:FlagFalse描述是否交换了数据的标志foriinrange(0,length1):由于越往后,越不要排这么多次数了。c1columns〔i〕代表前面柱子c2columns〔i1〕代表后面柱子ifc1。scalec2。scale:如果前面的柱子更高,则交换位置x1c1。xcor()保留前面柱子c1的x坐标x2c2。xcor()保留后面柱子c2的x坐标columns〔i〕c2让前面的柱子赋值为后面柱子columns〔i1〕c1让后面的柱子赋值为前面柱子columns〔i〕。setx(x1)交换列表中项目后,重新设置x坐标columns〔i1〕。setx(x2)交换列表中项目后,重新设置x坐标FlagTruescreen。update()sleep(0。1)lengthlength1ifFlagFalse:break如果一次都没有排序,则退出while循环 2。2。23dturtle法: 2。2。2。1来源:https:blog。csdn。netmagicdoubiarticledetails88843825 2。2。2。2效果图: 2。2。2。3代码三:fromturtleimportfromrandomimportimporttimedefbubblesort(rectanglelist):forpassnuminrange(0,101):foriinrange(0,10passnum1,1):ifrectanglelist〔i〕。numrectanglelist〔i1〕。num:rectanglelist〔i〕。replace(rectanglelist〔i1〕)time。sleep(0。5)休眠1秒classCube():definit(self,x,y,num,leng10):self。xxself。yyself。numnumself。sidelenlengself。createcube()defcreateside(self):fillcolor(639CD3)beginfill()left(170)forward(self。sidelen)right(80)forward(20self。num)right(100)forward(self。sidelen)right(80)forward(20self。num)endfill()setheading(0)恢复向右默认defcreatetop(self):fillcolor(95CEFF)penup()goto(self。x,self。y20self。num)pendown()beginfill()forward(20)left(170)forward(self。sidelen)left(10)forward(20)left(170)forward(self。sidelen)endfill()setheading(0)恢复向右默认defcreaterectangle(self):color(639CD3)penup()goto(self。x,self。y)pendown()柱的正面颜色fillcolor(green)beginfill()forxinrange(1,5):ifx21:n20else:n20self。numforward(n)left(90)endfill()defcreatecube(self):tracer(False)self。createrectangle()self。createside()self。createtop()tracer(True)deferaserectangle(self):setheading(0)color(white)penup()goto(self。x,self。y)pendown()fillcolor(white)beginfill()forxinrange(1,5):ifx21:n20else:n20self。numforward(n)left(90)endfill()deferaseside(self):fillcolor(white)beginfill()left(170)forward(self。sidelen)right(80)forward(20self。num)right(100)forward(self。sidelen)right(80)forward(20self。num)endfill()setheading(0)恢复向右默认deferasetop(self):fillcolor(white)penup()goto(self。x,self。y20self。num)pendown()beginfill()forward(20)left(170)forward(self。sidelen)left(10)forward(20)left(170)forward(self。sidelen)endfill()setheading(0)恢复向右默认deferasecube(self):tracer(False)self。eraserectangle()self。eraseside()self。erasetop()tracer(True)defreplace(self,n):self。erasecube()n。erasecube()self。num,n。numn。num,self。numself。createcube()n。createcube()ifnamemain:hideturtle()varlist()foriinrange(0,10):var。append(Cube(35i,0,randint(1,10)))bubblesort(var)done() 2。3opencv法: 2。3。1来源:https:blog。csdn。netu011983560articledetails106195385 2。3。2效果图: 2。3。3代码四:importnumpyasnpimportosimportcv2classDataseq():WHITE(255,255,255)RED(0,0,255)BLACK(0,0,0)YELLOW(0,127,255)definit(self,dataNone,sorttypefigure):self。sorttypesorttypeself。interval400原来是5,太小了注意与data数据最大值和最小值也有关系,与跳跃时间也有关self。inter2ifdataNone:print(therearenodatatosort!!!)os。exit()else:self。datadataself。maxdmax(self。data)最大值self。mindmin(self。data)最小值self。getfigure()self。Visualize()self。sortdata()defgetfigure(self):datanumlen(self。data)maxdmax(self。data)mindmin(self。data)self。figurenp。full((500(maxdmind)50,(datanum)(self。intervalself。inter),3),255,dtypenp。uint8)foriinrange(len(self。data)):self。figure〔50(self。data〔i〕mind)500:,(i)(self。intervalself。inter):(i)(self。intervalself。inter)self。interval〕self。YELLOWdefchoice(self,i,j):mindself。mindself。figure〔50(self。data〔i〕mind)500:,(i)(self。intervalself。inter):(i)(self。intervalself。inter)self。interval〕self。BLACKself。figure〔50(self。data〔j〕mind)500:,(j)(self。intervalself。inter):(j)(self。intervalself。inter)self。interval〕self。BLACKself。Visualize()defchange(self,i,j):mindself。mindself。figure〔50(self。data〔i〕mind)500:,(i)(self。intervalself。inter):(i)(self。intervalself。inter)self。interval〕self。WHITEself。figure〔50(self。data〔j〕mind)500:,(j)(self。intervalself。inter):(j)(self。intervalself。inter)self。interval〕self。WHITEindataself。data〔i〕self。data〔i〕self。data〔j〕self。data〔j〕indataself。figure〔50(self。data〔i〕mind)500:,(i)(self。intervalself。inter):(i)(self。intervalself。inter)self。interval〕self。BLACKself。figure〔50(self。data〔j〕mind)500:,(j)(self。intervalself。inter):(j)(self。intervalself。inter)self。interval〕self。BLACKself。Visualize()defVisualize(self):figure1self。figurecv2。namedWindow(img,cv2。WINDOWNORMAL)cv2。imshow(img,figure1)cv2。waitKey(1000)defsortdata(self):fordiinrange(len(self。data)):fordjinrange(len(self。data)di1):self。choice(dj,dj1)ifself。data〔dj〕self。data〔dj1〕:self。change(dj,dj1)self。getfigure()datatDataseq(〔10,20,30,15,25,18〕,sort)datat。Visualize()cv2。destroyAllWindows() 2。4pygame法: 2。4。1来源:https:github。comzetaleeeVisualizationalgorithm 2。4。2效果图: 2。4。3代码五:importpygamefromrandomimportrandintgap10竖条的间隔width30竖条的宽度screenSize(600,250)显示屏幕的尺寸barXPosition〔〕竖条在坐标轴的位置Bars〔〕竖条对象列表生成颜色classcolor(object):staticmethoddefRandomColor():r,g,brandint(0,225),randint(0,255),randint(0,255)return(r,g,b)staticmethoddefCalculateColor(self,num):passclassbar(object):definit(self,n,num,screen,width30):self。nnself。locationXbarXPosition〔n〕self。locationYscreenSize〔1〕50numself。numnumself。colorcolor。RandomColor()self。widthwidthself。fontpygame。font。Font(None,20)self。screenscreen绘制竖条及其上方的数字defBarDraw(self):pygame。draw。rect(self。screen,self。color,((self。locationX,self。locationY),(self。width,self。num)))self。txtself。font。render({}。format(self。num),True,self。color)self。screen。blit(self。txt,(self。locationX5,self。locationY20))移动竖条,flag是用于判断移动方向True向右False向左defmove(self,flag):pace2移动的步长消除移动前的竖条pygame。draw。rect(self。screen,(255,255,235),((self。locationX,self。locationY),(self。width,self。num)))ifflag:self。locationXpaceelse:self。locationXpace绘制移动后的竖条pygame。draw。rect(self。screen,self。color,((self。locationX,self。locationY),(self。width,self。num)))交换相邻两个竖条defChangeLocation(self,otherBall):清除当前位置图像与文字pygame。draw。rect(self。screen,(255,255,235),((self。locationX,self。locationY20),(self。width,self。num20)))pygame。draw。rect(otherBall。screen,(255,255,235),((otherBall。locationX,otherBall。locationY20),(otherBall。width,otherBall。num20)))竖条移动的动画forninrange(20):self。move(True)otherBall。move(False)pygame。time。delay(40)pygame。display。flip()移动后,重新写上竖条对应的数字self。screen。blit(self。txt,(self。locationX5,self。locationY20))otherBall。screen。blit(otherBall。txt,(otherBall。locationX5,otherBall。locationY20))交换竖条对象在列表的位置,同时交换排位数字Bars〔self。n〕,Bars〔otherBall。n〕Bars〔otherBall。n〕,Bars〔self。n〕self。n,otherBall。notherBall。n,self。npygame。display。flip()pygame。time。delay(200)此延时控制排序动画的快慢冒泡排序defalgorithm(nums):foriinrange(len(nums)1):forjinrange(len(nums)1i):ifnums〔j〕nums〔j1〕:Bars〔j〕。ChangeLocation(Bars〔j1〕)nums〔j〕,nums〔j1〕nums〔j1〕,nums〔j〕计算十二个竖条在轴上的位置defbarX(gap,width,barXs):forninrange(12):barX50gap(gapwidth)nbarXs。append(barX)defmain():nums〔〕pygame。init()screenpygame。display。setmode(screenSize)pygame。display。setcaption(算法)标题screen。fill((255,255,235))背景色barX(gap,width,barXPosition)计算bar位置并存于barXspygame。draw。aaline(screen,(0,255,0),(50,screenSize〔1〕50),(screenSize〔0〕50,screenSize〔1〕50))绘制坐标轴pygame。display。flip()生成十二个竖条并绘制forninrange(12):numrandint(20,160)tempBarbar(n,num,screen)tempBar。BarDraw()nums。append(num)Bars。append(tempBar)pygame。time。delay(50)此处延时是为了开始时演示动画效果pygame。display。flip()algorithm(nums)排序等待关闭窗口事件runTruewhilerun:foreventinpygame。event。get():ifevent。typepygame。QUIT:runFalseifnamemain:main() 自己整理并分享出来 喜欢的人,请点赞、关注、评论、转发和收藏。