Merge pull request #14 from abrarShariar/master
Added implementations for factorial, fibonacci, linear search and jump searchpull/16/head
commit
cc26ad7dce
@ -0,0 +1,15 @@
|
|||||||
|
package main
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func factorial(num int) int {
|
||||||
|
if num == 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return num * factorial(num - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
num := 10
|
||||||
|
result := factorial(num)
|
||||||
|
fmt.Println(result)
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package main
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
//using recursion
|
||||||
|
func fibo(num int) int {
|
||||||
|
if num <= 1 {
|
||||||
|
return num
|
||||||
|
}
|
||||||
|
return fibo(num -1) + fibo(num - 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main(){
|
||||||
|
num := 10
|
||||||
|
result := fibo(num)
|
||||||
|
fmt.Println(result)
|
||||||
|
}
|
@ -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)
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package main
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func search(arr []int, key int) int {
|
||||||
|
for i := 0; i < len(arr); i++ {
|
||||||
|
if arr[i] == key {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
|
||||||
|
searchValue := 100
|
||||||
|
arr := []int{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
|
||||||
|
fmt.Println(arr)
|
||||||
|
|
||||||
|
found := search(arr, searchValue)
|
||||||
|
|
||||||
|
if found == -1 {
|
||||||
|
fmt.Println("Key not found")
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Key found at position: %d\n", found)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue