How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Nemerle programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Nemerle 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 Nemerle programming language
Source code in the nemerle programming language
using System.Console;
using Nemerle.English;
module InsertSort
{
public static Sort(this a : array[int]) : void
{
mutable value = 0; mutable j = 0;
foreach (i in [1 .. (a.Length - 1)])
{
value = a[i]; j = i - 1;
while (j >= 0 and a[j] > value)
{
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = value;
}
}
Main() : void
{
def arr = array[1, 4, 8, 3, 8, 3, 5, 2, 6];
arr.Sort();
foreach (i in arr) Write($"$i ");
}
}
You may also check:How to resolve the algorithm Longest common subsequence step by step in the Perl programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the Befunge programming language
You may also check:How to resolve the algorithm Enforced immutability step by step in the Z80 Assembly programming language
You may also check:How to resolve the algorithm Random Latin squares step by step in the Wren programming language
You may also check:How to resolve the algorithm Concurrent computing step by step in the Ada programming language