Commit 2daebe81 authored by Ilia Prokhorov's avatar Ilia Prokhorov
Browse files

Binary insertion sort implemented in GO

parent 5a44c93a
package main
import "fmt"
import (
"fmt"
"math/rand"
"time"
)
#TODO
const numbersCount = 20
const maximalNumber = 100
func binarySearch(numbers []int, low int, high int) int {
return 0
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() {
numbers := []int{1, 2, 3}
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++ {
var lessIndex = binarySearch(numbers, 0, 0)
var lessNumber = numbers[i]
numbers[i] = numbers[lessIndex]
numbers[lessIndex] = lessNumber
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)
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment