How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the PureBasic programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the PureBasic 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 PureBasic programming language
Source code in the purebasic programming language
;sorts an array of integers
Procedure cocktailSort(Array a(1))
Protected index, hasChanged, low, high
low = 0
high = ArraySize(a()) - 1
Repeat
hasChanged = #False
For index = low To high
If a(index) > a(index + 1)
Swap a(index), a(index + 1)
hasChanged = #True
EndIf
Next
high - 1
If hasChanged = #False
Break ;we can exit the outer loop here if no changes were made
EndIf
hasChanged = #False
For index = high To low Step -1
If a(index) > a(index + 1)
Swap a(index), a(index + 1)
hasChanged = #True
EndIf
Next
low + 1
Until hasChanged = #False ;if no elements have been changed, then the array is sorted
EndProcedure
You may also check:How to resolve the algorithm Environment variables step by step in the Go programming language
You may also check:How to resolve the algorithm Flatten a list step by step in the Scala programming language
You may also check:How to resolve the algorithm Continued fraction step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Color wheel step by step in the Plain English programming language
You may also check:How to resolve the algorithm Bitmap/Bézier curves/Cubic step by step in the Lua programming language