How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the FreeBASIC programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the FreeBASIC programming language
Table of Contents
Problem Statement
The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the FreeBASIC programming language
Source code in the freebasic programming language
' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Sub cocktailsort(bs() As Long)
' sort from lower bound to the highter bound
' array's can have subscript range from -2147483648 to +2147483647
Dim As Long lb = LBound(bs)
Dim As Long ub = UBound(bs) -1
Dim As Long done, i
Do
done = 0 ' going up
For i = lb To ub
If bs(i) > bs(i +1) Then
Swap bs(i), bs(i +1)
done = 1
End If
Next
ub = ub -1
If done = 0 Then Exit Do ' 0 means the array is sorted
done = 0 ' going down
For i = ub To lb Step -1
If bs(i) > bs(i +1) Then
Swap bs(i), bs(i +1)
done = 1
End If
Next
lb = lb +1
Loop Until done = 0 ' 0 means the array is sorted
End Sub
' ------=< MAIN >=------
Dim As Long i, array(-7 To 7)
Dim As Long a = LBound(array), b = UBound(array)
Randomize Timer
For i = a To b : array(i) = i : Next
For i = a To b ' little shuffle
Swap array(i), array(Int(Rnd * (b - a +1)) + a)
Next
Print "unsorted ";
For i = a To b : Print Using "####"; array(i); : Next : Print
cocktailsort(array()) ' sort the array
Print " sorted ";
For i = a To b : Print Using "####"; array(i); : Next : Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
You may also check:How to resolve the algorithm Reduced row echelon form step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Non-continuous subsequences step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Idiomatically determine all the characters that can be used for symbols step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Unix/ls step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Steffensen's method step by step in the FreeBASIC programming language