How to resolve the algorithm Sorting algorithms/Cocktail sort with shifting bounds step by step in the AutoHotkey programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Cocktail sort with shifting bounds step by step in the AutoHotkey programming language

Table of Contents

Problem Statement

The   cocktail sort   is an improvement on the   Bubble Sort.

A cocktail sort is also known as:

The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved.

Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: %   indicates a comment,   and   deal   indicates a   swap.

Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Cocktail sort with shifting bounds step by step in the AutoHotkey programming language

Source code in the autohotkey programming language

cocktailShakerSort(A){
    beginIdx := 1
    endIdx := A.Count() - 1
    while (beginIdx <= endIdx) {
        newBeginIdx := endIdx
        newEndIdx := beginIdx
        ii := beginIdx
        while (ii <= endIdx) {
            if (A[ii] > A[ii + 1]) {
                tempVal := A[ii], A[ii] := A[ii+1], A[ii+1] := tempVal
                newEndIdx := ii
            }
            ii++
        }
        endIdx := newEndIdx - 1
        ii := endIdx
        while (ii >= beginIdx) {
            if (A[ii] > A[ii + 1]) {
                tempVal := A[ii], A[ii] := A[ii+1], A[ii+1] := tempVal
                newBeginIdx := ii
            }
            ii--
        }
        beginIdx := newBeginIdx + 1
    }
}


A := [8,6,4,3,5,2,7,1]
cocktailShakerSort(A)
for k, v in A
    output .= v ", "
MsgBox % "[" Trim(output, ", ") "]"     ; show output


  

You may also check:How to resolve the algorithm Van Eck sequence step by step in the BCPL programming language
You may also check:How to resolve the algorithm Sorting algorithms/Counting sort step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Brace expansion step by step in the C++ programming language
You may also check:How to resolve the algorithm Percolation/Bond percolation step by step in the D programming language
You may also check:How to resolve the algorithm String concatenation step by step in the Slope programming language