How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Action! programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Action! 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 Action! programming language

Source code in the action! programming language

PROC PrintArray(INT ARRAY a INT size)
  INT i

  Put('[)
  FOR i=0 TO size-1
  DO
    IF i>0 THEN Put(' ) FI
    PrintI(a(i))
  OD
  Put(']) PutE()
RETURN

PROC CoctailSort(INT ARRAY a INT size)
  INT i,tmp
  BYTE swapped

  DO
    swapped=0
    i=0
    WHILE i
    DO
      IF a(i)>a(i+1) THEN
        tmp=a(i) a(i)=a(i+1) a(i+1)=tmp
        swapped=1
      FI
      i==+1
    OD

    IF swapped=0 THEN EXIT FI

    swapped=0
    i=size-1
    WHILE i>=0
    DO
      IF a(i)>a(i+1) THEN
        tmp=a(i) a(i)=a(i+1) a(i+1)=tmp
        swapped=1
      FI
      i==-1
    OD

  UNTIL swapped=0
  OD
RETURN

PROC Test(INT ARRAY a INT size)
  PrintE("Array before sort:")
  PrintArray(a,size)
  CoctailSort(a,size)
  PrintE("Array after sort:")
  PrintArray(a,size)
  PutE()
RETURN

PROC Main()
  INT ARRAY
    a(10)=[1 4 65535 0 3 7 4 8 20 65530],
    b(21)=[10 9 8 7 6 5 4 3 2 1 0
      65535 65534 65533 65532 65531
      65530 65529 65528 65527 65526],
    c(8)=[101 102 103 104 105 106 107 108],
    d(12)=[1 65535 1 65535 1 65535 1
      65535 1 65535 1 65535]
  
  Test(a,10)
  Test(b,21)
  Test(c,8)
  Test(d,12)
RETURN

  

You may also check:How to resolve the algorithm Split a character string based on change of character step by step in the Factor programming language
You may also check:How to resolve the algorithm Binary search step by step in the Euphoria programming language
You may also check:How to resolve the algorithm Sum and product of an array step by step in the bc programming language
You may also check:How to resolve the algorithm Monty Hall problem step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Periodic table step by step in the Phix programming language