A-A+

一个很容易编写的排序例程是冒泡排序。程序只是简单地反复扫描待排序的所有元素。在每次遍历时 程

2022-08-12 10:10:32 问答库 阅读 195 次

问题详情

一个很容易编写的排序例程是冒泡排序。程序只是简单地反复扫描待排序的所有元素。在每次遍历时,程序都会把每个元素与它后面的一个元素作比较,如果它们处于逆序中,则重排它们的顺序。例如,要对下面的列表进行排序: 6 7 3 1 4 冒泡排序首先比较6和7。它们处于正确的顺序,因此再比较7和3。它们处于逆序中,因此冒泡排序交换7和3,然后再比较7和1。数字7和1处于逆序中,因此冒泡排序交换它们,然后比较7和4。再一次,顺序不正确,因此它交换7和4。第一次扫描结束后得到: 6 3 1 4 7 从左到右再扫描一次后得到: 3 1 4 6 7 再次从左到右扫描后得到正确的顺序: 1 3 4 6 7 编写冒泡排序的伪代码。


请帮忙给出正确答案和分析,谢谢!

参考答案

正确答案:bubbleSort(1ist)length <--length of list//look through the whole list to find//mis-ordered pairsand continue until//we get through the whole list without//swapping any pairsdo{//start at the left end of the 1ist:index=1swapped_pair<--faiseindex <--1while index<=length一1{//if this pair is mis-orderedswap themif 1ist[index]>list[index+1]{swap(list[index]1ist[index+1])swapped_pair=true//increment the index to look at the//next pair upindex<--index+1}}//quit only when we have gone through the whole//list and found it unnecessary to swap any pair}while(swapped=true)end
bubbleSort(1ist)length<--lengthoflist//lookthroughthewholelisttofind//mis-orderedpairs,andcontinueuntil//wegetthroughthewholelistwithout//swappinganypairsdo{//startattheleftendofthe1ist:index=1swapped_pair<--faiseindex<--1whileindex<=length一1{//ifthispairismis-ordered,swapthemif1ist[index]>list[index+1]{swap(list[index],1ist[index+1])swapped_pair=true//incrementtheindextolookatthe//nextpairupindex<--index+1}}//quitonlywhenwehavegonethroughthewhole//listandfounditunnecessarytoswapanypair}while(swapped=true)end

考点:元素,程序