How to resolve the algorithm Sorting algorithms/Permutation 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/Permutation sort step by step in the Common Lisp programming language

Table of Contents

Problem Statement

Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Permutation sort step by step in the Common Lisp programming language

Source code in the common programming language

(defun factorial (n)
  (loop for result = 1 then (* i result)
        for i from 2 to n
        finally (return result)))

(defun nth-permutation (k sequence)
  (if (zerop (length sequence))
      (coerce () (type-of sequence))
      (let ((seq (etypecase sequence
                   (vector (copy-seq sequence))
                   (sequence (coerce sequence 'vector)))))
        (loop for j from 2 to (length seq)
              do (setq k (truncate (/ k (1- j))))
              do (rotatef (aref seq (mod k j))
                          (aref seq (1- j)))
              finally (return (coerce seq (type-of sequence)))))))

(defun sortedp (fn sequence)
  (etypecase sequence
    (list (loop for previous = #1='#:foo then i
                for i in sequence
                always (or (eq previous #1#)
                           (funcall fn i previous))))
    ;; copypasta
    (vector (loop for previous = #1# then i
                  for i across sequence
                  always (or (eq previous #1#)
                             (funcall fn i previous))))))

(defun permutation-sort (fn sequence)
  (loop for i below (factorial (length sequence))
        for permutation = (nth-permutation i sequence)
        when (sortedp fn permutation)
          do (return permutation)))


CL-USER> (time (permutation-sort #'> '(8 3 10 6 1 9 7 2 5 4)))
Evaluation took:
  5.292 seconds of real time
  5.204325 seconds of total run time (5.176323 user, 0.028002 system)
  [ Run times consist of 0.160 seconds GC time, and 5.045 seconds non-GC time. ]
  98.34% CPU
  12,337,938,025 processor cycles
  611,094,240 bytes consed
  
(1 2 3 4 5 6 7 8 9 10)


  

You may also check:How to resolve the algorithm Factorial step by step in the Little Man Computer programming language
You may also check:How to resolve the algorithm Narcissistic decimal number step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Four is magic step by step in the Julia programming language
You may also check:How to resolve the algorithm Bitmap step by step in the Action! programming language
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the LOLCODE programming language