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

Source code in the 11l programming language

F cocktailshiftingbounds(&A)
   V beginIdx = 0
   V endIdx = A.len - 1

   L beginIdx <= endIdx
      V newBeginIdx = endIdx
      V newEndIdx = beginIdx
      L(ii) beginIdx .< endIdx
         I A[ii] > A[ii + 1]
            swap(&A[ii + 1], &A[ii])
            newEndIdx = ii
      endIdx = newEndIdx

      L(ii) (endIdx .< beginIdx - 1).step(-1)
         I A[ii] > A[ii + 1]
            swap(&A[ii + 1], &A[ii])
            newBeginIdx = ii
      beginIdx = newBeginIdx + 1

V test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailshiftingbounds(&test1)
print(test1)

  

You may also check:How to resolve the algorithm Dynamic variable names step by step in the Python programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Non-decimal radices/Output step by step in the HicEst programming language
You may also check:How to resolve the algorithm Find largest left truncatable prime in a given base step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Infinity step by step in the Euphoria programming language