How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Common Lisp programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Common Lisp 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 Common Lisp programming language
Source code in the common programming language
(defun cocktail-sort-vector (vector predicate &aux (len (length vector)))
(labels ((scan (start step &aux swapped)
(loop for i = start then (+ i step) while (< 0 i len) do
(when (funcall predicate (aref vector i)
(aref vector (1- i)))
(rotatef (aref vector i)
(aref vector (1- i)))
(setf swapped t)))
swapped))
(loop while (and (scan 1 1)
(scan (1- len) -1))))
vector)
(defun cocktail-sort (sequence predicate)
(etypecase sequence
(vector (cocktail-sort-vector sequence predicate))
(list (map-into sequence 'identity
(cocktail-sort-vector (coerce sequence 'vector)
predicate)))))
You may also check:How to resolve the algorithm Handle a signal step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Zeckendorf arithmetic step by step in the C++ programming language
You may also check:How to resolve the algorithm Draw a cuboid step by step in the Ruby programming language
You may also check:How to resolve the algorithm Binary digits step by step in the Forth programming language
You may also check:How to resolve the algorithm Averages/Arithmetic mean step by step in the NewLISP programming language