Merge pull request #14 from abrarShariar/master

Added implementations for factorial, fibonacci, linear search and jump search
pull/16/head
0xAX 6 years ago committed by GitHub
commit cc26ad7dce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -32,6 +32,8 @@ Algorithms
#### Searching
* [binary search](https://en.wikipedia.org/wiki/Binary_search_algorithm)
* [linear search](https://en.wikipedia.org/wiki/Linear_search)
* [jump search](https://en.wikipedia.org/wiki/Jump_search)
#### Collections
@ -43,7 +45,9 @@ Algorithms
#### Numerical
* [gcd](https://en.wikipedia.org/wiki/Greatest_common_divisor)
* [factorial](https://en.wikipedia.org/wiki/Factorial)
* [fibonacci](https://en.wikipedia.org/wiki/Fibonacci_number)
Contribution
------------

@ -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…
Cancel
Save