How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the VBA programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the VBA 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 VBA programming language
Source code in the vba programming language
Option Base 1
Private Function insertion_sort(s As Variant) As Variant
Dim temp As Variant
Dim j As Integer
For i = 2 To UBound(s)
temp = s(i)
j = i - 1
Do While s(j) > temp
s(j + 1) = s(j)
j = j - 1
If j = 0 Then Exit Do
Loop
s(j + 1) = temp
Next i
insertion_sort = s
End Function
Public Sub main()
s = [{4, 15, "delta", 2, -31, 0, "alpha", 19, "gamma", 2, 13, "beta", 782, 1}]
Debug.Print "Before: ", Join(s, ", ")
Debug.Print "After: ", Join(insertion_sort(s), "' ")
End Sub
You may also check:How to resolve the algorithm Palindrome detection step by step in the Quackery programming language
You may also check:How to resolve the algorithm Logistic curve fitting in epidemiology step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Order disjoint list items step by step in the 11l programming language
You may also check:How to resolve the algorithm Matrix multiplication step by step in the S-lang programming language
You may also check:How to resolve the algorithm Terminal control/Ringing the terminal bell step by step in the Mathematica/Wolfram Language programming language