Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add binary insertion sort algorithm #671

Merged
merged 4 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions sort/binaryinsertionsort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Binary Insertion Sort
// description: Implementation of binary insertion sort in Go
// details: Binary Insertion Sort is a variation of
// Insertion sort in which proper location to
// insert the selected element is found using the
// Binary search algorithm.
// ref: https://www.geeksforgeeks.org/binary-insertion-sort

package sort

import "github.com/TheAlgorithms/Go/constraints"

func BinaryInsertion[T constraints.Ordered](arr []T) []T {
for currentIndex := 1; currentIndex < len(arr); currentIndex++ {
temporary := arr[currentIndex]
low := 0
high := currentIndex - 1

for low <= high {
mid := low + (high-low)/2
if arr[mid] > temporary {
high = mid - 1
} else {
low = mid + 1
}
}

for itr := currentIndex; itr > low; itr-- {
arr[itr] = arr[itr-1]
}

arr[low] = temporary
}
return arr
}
9 changes: 8 additions & 1 deletion sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,10 @@ func testFramework(t *testing.T, sortingFunction func([]int) []int) {
}
}

//BEGIN TESTS
// BEGIN TESTS
func TestBinaryInsertion(t *testing.T) {
testFramework(t, sort.BinaryInsertion[int])
}

func TestBubble(t *testing.T) {
testFramework(t, sort.Bubble[int])
Expand Down Expand Up @@ -219,6 +222,10 @@ func benchmarkFramework(b *testing.B, f func(arr []int) []int) {

//BEGIN BENCHMARKS

func BenchmarkBinaryInsertion(b *testing.B) {
benchmarkFramework(b, sort.BinaryInsertion[int])
}

func BenchmarkBubble(b *testing.B) {
benchmarkFramework(b, sort.Bubble[int])
}
Expand Down