From 38b23e88391603b780e52c3aa3b1da314d0b7afd Mon Sep 17 00:00:00 2001 From: abrarShariar Date: Fri, 13 Jul 2018 02:17:33 +0600 Subject: [PATCH] jump search --- searching/jumpSearch.go | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 searching/jumpSearch.go diff --git a/searching/jumpSearch.go b/searching/jumpSearch.go new file mode 100644 index 0000000..4a153d4 --- /dev/null +++ b/searching/jumpSearch.go @@ -0,0 +1,44 @@ +package main +import "fmt" +import "math" + +func jumpSearch(arr []int, key int) int { + + //block size to jump + sz := len(arr) + step := int(math.Sqrt(float64(sz))) + prev := 0 + + //finding the block + for arr[int(math.Min(float64(step), float64(sz))) - 1] < key { + prev = step + step += int(math.Sqrt(float64(sz))) + if prev >= sz { + return -1 + } + } + + //linear search the block + for arr[prev] < key { + prev++ + if prev == int(math.Min(float64(step), float64(sz))) { + return -1 + } + } + + if arr[prev] == key { + return prev + } + return -1 +} + + +func main() { + + arr := []int { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 } + key := 55 + + index := jumpSearch(arr, key) + fmt.Println(index) + +}