VB.Net冒泡排序代码(有详细解释)
FunctionBubbleSort(ByValArAsArray)
DimiAsInteger
DimjAsInteger
DimTemp'不定义变量类型,以自动适应数组Ar的类型
DimFlagAsBoolean
DimnAsInteger =Ar.Length - 1
Fori = 1Ton
Flag =False
'从第1个元素开始,比较每两个相邻元素的大小,让大元素下沉,小元素上浮
'经过一轮循环,可使数组中最大元素下沉到数组最底部
'进入下一轮循环,只对前 n - i 个元素进行相邻比较(已排到后面的不用比较)
Forj = 0Ton - i
IfAr(j) > Ar(j + 1)Then
Temp = Ar(j)
Ar(j) = Ar(j + 1)
Ar(j + 1) = Temp
Flag =True'如果有排序行为,则设为 True
EndIf
Next
IfFlag =FalseThen'如未排序,说明已完成整个排序过程,退出
ExitFor
EndIf
Next
EndFunction
示例
DimA()AsInteger= {5,7,2,4,11,9,6}
BubbleSort(A)结果会是{2,5,6,11}
DimB()AsString= {"DD","GG","CC","FF","JJ","AA","BB"}
BubbleSort(B)结果会是{"AA","BB","DD","JJ"}