How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the AutoHotkey programming language

Published on 12 May 2024 09:40 PM

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

Source code in the autohotkey programming language

MsgBox % InsertionSort("")
MsgBox % InsertionSort("xxx")
MsgBox % InsertionSort("3,2,1")
MsgBox % InsertionSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z")

InsertionSort(var) {                     ; SORT COMMA SEPARATED LIST
   StringSplit a, var, `,                ; make array, size = a0
   Loop % a0-1 {
      i := A_Index+1, v := a%i%, j := i-1
      While j>0 and a%j%>v
         u := j+1, a%u% := a%j%, j--
      u := j+1, a%u% := v
   }
   Loop % a0                             ; construct string from sorted array
      sorted .= "," . a%A_Index%
   Return SubStr(sorted,2)               ; drop leading comma
}


  

You may also check:How to resolve the algorithm Terminal control/Ringing the terminal bell step by step in the Ruby programming language
You may also check:How to resolve the algorithm Hello world/Newline omission step by step in the Oforth programming language
You may also check:How to resolve the algorithm Sudan function step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Loops/N plus one half step by step in the Pop11 programming language
You may also check:How to resolve the algorithm Floyd-Warshall algorithm step by step in the zkl programming language