Binary Insertion Sort

Binary Insertion Sort is a variant of insertion sort in which the insertion position is determined using a binary search. The time complexity of the algorithm is O(n2)

The algorithm works like this:

  1. Loop from zero to end of list
  2. In the loop, a number is selected for sorting, the number is stored in a separate variable
  3. Binary search looks for the index to insert this number against the numbers on the left
  4. After finding the index, the numbers on the left are shifted one position to the right, starting at the insertion index. The process will erase the number to be sorted.
  5. The previously stored number is inserted at the insertion index
  6. At the end of the loop, the entire list will be sorted

During a binary search, it is possible that the number will not be found, but the index is not returned. Due to the peculiarities of the binary search, the number closest to the desired one will be found, then to return the index it will be necessary to compare it with the desired one, if the desired one is less, then the desired one should be at the index on the left, and if it is greater or equal, then on the right.

Source code in Go:

package main

import (
	"fmt"
	"math/rand"
	"time"
)

const numbersCount = 20
const maximalNumber = 100

func binarySearch(numbers []int, item int, low int, high int) int {
	for high > low {
		center := (low + high) / 2
		if numbers[center] < item { low = center + 1 } else if numbers[center] > item {
			high = center - 1
		} else {
			return center
		}
	}

	if numbers[low] < item {
		return low + 1
	} else {
		return low
	}
}

func main() {
	rand.Seed(time.Now().Unix())
	var numbers [numbersCount]int
	for i := 0; i < numbersCount; i++ {
		numbers[i] = rand.Intn(maximalNumber)
	}
	fmt.Println(numbers)

	for i := 1; i < len(numbers); i++ { searchAreaLastIndex := i - 1 insertNumber := numbers[i] insertIndex := binarySearch(numbers[:], insertNumber, 0, searchAreaLastIndex) for x := searchAreaLastIndex; x >= insertIndex; x-- {
			numbers[x+1] = numbers[x]
		}
		numbers[insertIndex] = insertNumber
	}
	fmt.Println(numbers)
}

Links

https://gitlab.com/demensdeum/algorithms/-/blob/master/sortAlgorithms/binaryInsertionSort/binaryInsertionSort.go

References

https://www.geeksforgeeks.org/binary-insertion-sort/
https://www.youtube.com/watch?v=-OVB5pOZJug