How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Clojure programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Clojure programming language
Table of Contents
Problem Statement
An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:
The algorithm is as follows (from wikipedia): Writing the algorithm for integers will suffice.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Clojure programming language
Source code in the clojure programming language
(defn insertion-sort [coll]
(reduce (fn [result input]
(let [[less more] (split-with #(< % input) result)]
(concat less [input] more)))
[]
coll))
(defn in-sort! [data]
(letfn [(insert ([raw x](insert [] raw x))
([sorted [y & raw] x]
(if (nil? y) (conj sorted x)
(if (<= x y ) (concat sorted [x,y] raw)
(recur (conj sorted y) raw x )))))]
(reduce insert [] data)))
;Usage:(in-sort! [6,8,5,9,3,2,1,4,7])
;Returns: [1 2 3 4 5 6 7 8 9]
You may also check:How to resolve the algorithm Set puzzle step by step in the Nim programming language
You may also check:How to resolve the algorithm Collections step by step in the PL/I programming language
You may also check:How to resolve the algorithm Loops/N plus one half step by step in the Spin programming language
You may also check:How to resolve the algorithm Numeric error propagation step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Ray-casting algorithm step by step in the BASIC programming language