How to resolve the algorithm Sorting algorithms/Cocktail sort with shifting bounds step by step in the Arturo 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 Arturo 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 Arturo programming language

Source code in the arturo programming language

cocktailShiftSort: function [items][
    a: new items
    beginIdx: 0
    endIdx: (size a)-2

    while [beginIdx =< endIdx][
        newBeginIdx: endIdx
        newEndIdx: beginIdx

        loop beginIdx..endIdx 'i [
            if a\[i] > a\[i+1] [
                tmp: a\[i]
                a\[i]: a\[i+1]
                a\[i+1]: tmp
                newEndIdx: i
            ]
        ]

        endIdx: newEndIdx - 1

        loop endIdx..beginIdx 'i [
            if a\[i] > a\[i+1] [
                tmp: a\[i]
                a\[i]: a\[i+1]
                a\[i+1]: tmp
                newBeginIdx: i
            ]
        ]

        beginIdx: newBeginIdx - 1
    ]
    return a
]

print cocktailShiftSort [3 1 2 8 5 7 9 4 6]


  

You may also check:How to resolve the algorithm Dragon curve step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Safe primes and unsafe primes step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Sum of squares step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Pell's equation step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Terminal control/Clear the screen step by step in the Java programming language