How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the EMal programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the EMal 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 EMal programming language
Source code in the emal programming language
fun insertionSort = void by List a # sort list in place
for int i = 1; i < a.length; ++i
var v = a[i]
int j
for j = i - 1; j >= 0 and a[j] > v; --j
a[j + 1] = a[j]
end
a[j + 1] = v
end
end
List lists = List[ # a list of lists
int[4, 65, 2, -31, 0, 99, 83, 782, 1],
real[5.17, 2, 5.12],
text["this", "is", "insertion", "sort"]]
for each List list in lists
writeLine("Before: " + text!list) # list as text
insertionSort(list)
writeLine("After : " + text!list)
writeLine()
end
You may also check:How to resolve the algorithm N'th step by step in the Lambdatalk programming language
You may also check:How to resolve the algorithm A+B step by step in the Acornsoft Lisp programming language
You may also check:How to resolve the algorithm Sort numbers lexicographically step by step in the Ada programming language
You may also check:How to resolve the algorithm Anagrams step by step in the J programming language
You may also check:How to resolve the algorithm Pernicious numbers step by step in the Fōrmulæ programming language