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 1 commit
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
34 changes: 34 additions & 0 deletions sort/binaryinsertionsort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// 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.

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

Check failure on line 19 in sort/binaryinsertionsort.go

View workflow job for this annotation

GitHub Actions / Code style and tests

File is not `gofmt`-ed with `-s` (gofmt)
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
}
7 changes: 7 additions & 0 deletions sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,10 @@
}
}

//BEGIN TESTS

Check failure on line 78 in sort/sorts_test.go

View workflow job for this annotation

GitHub Actions / Code style and tests

File is not `gofmt`-ed with `-s` (gofmt)
func TestBinaryInsertion(t *testing.T) {
testFramework(t, sort.BinaryInsertion[int])
}

func TestBubble(t *testing.T) {
testFramework(t, sort.Bubble[int])
Expand Down Expand Up @@ -214,6 +217,10 @@

//BEGIN BENCHMARKS

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

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