Code archives/Algorithms/Bubble Sorting
This code has been declared by its author to be Public Domain code.
Download source code
| |||||
| Simple array bubble sorting | |||||
; Note this is made in BlitzPlus, the print commands may not work the same in Blitz3D length%=5 Dim Array(length%) Print "==Creating Random List==" For i%=0 To length% Array(i%)=Rand(1,300) Print Array(i%) Next Print "==Bubble Sorting List==" For i%=length% To 1 Step -1 For j%=0 To i%-1 If Array(j%)>Array(j%+1) Temp%=Array(j%) Array(j%)=Array(j%+1) Array(j%+1)=Temp% EndIf Next Next Time%=MilliSecs()-Start% Print "Took " +Time%+ " ms to calculate." Print "==Sort Result==" For i%=0 To length% Print Array(i%) Next Print "====" Repeat Forever |
Comments
| ||
Check out this example. It contains a Swap variable so that it can abort the loop as soon as the list is sorted. Much faster for lists that are already fairly well sorted:
For i = TotalFruit-1 To 0 Step - 1
Local swap = 0
For j=1 To i
If FruitArray(j)\y > FruitArray(j-1)\y
swap = 1
Local tempf.fruit = FruitArray(j)
FruitArray(j) = FruitArray(j-1)
FruitArray(j-1) = tempf
EndIf
Next
If swap = 0 Then Exit
Next
|
Code Archives Forum