October 17, 2021, 11:36:10

Author Topic: [bb] Bubble Sorting by Regular K [ 1+ years ago ]  (Read 551 times)

Offline BlitzBot

  • Jr. Member
  • **
  • Posts: 1
[bb] Bubble Sorting by Regular K [ 1+ years ago ]
« on: June 29, 2017, 00:28:42 »
Title : Bubble Sorting
Author : Regular K
Posted : 1+ years ago

Description : Simple array bubble sorting

Code :
Code: BlitzBasic
  1. ; Note this is made in BlitzPlus, the print commands may not work the same in Blitz3D
  2. length%=5
  3. Dim Array(length%)
  4. Print "==Creating Random List=="
  5. For i%=0 To length%
  6.         Array(i%)=Rand(1,300)
  7.         Print Array(i%)
  8. Next
  9. Print "==Bubble Sorting List=="
  10. For i%=length% To 1 Step -1
  11.         For j%=0 To i%-1
  12.                 If Array(j%)>Array(j%+1)
  13.                         Temp%=Array(j%)
  14.                         Array(j%)=Array(j%+1)
  15.                         Array(j%+1)=Temp%
  16.                 EndIf
  17.         Next
  18. Next
  19. Time%=MilliSecs()-Start%
  20. Print "Took " +Time%+ " ms to calculate."
  21. Print "==Sort Result=="
  22. For i%=0 To length%
  23.         Print Array(i%)
  24. Next
  25. Print "===="
  26. Repeat
  27. Forever


Comments :


Grey Alien(Posted 1+ years ago)

 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:
Code: [Select]
   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


 

SimplePortal 2.3.6 © 2008-2014, SimplePortal