-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.go
More file actions
60 lines (54 loc) · 1.17 KB
/
binary_search.go
File metadata and controls
60 lines (54 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package binarySearch
// FOR INTS IN A SLICE Positive & negative numbers
func ReturnNewBinarySort(nums []int, target int) []int{
//address edge case of a empty/nil slice being passed in
if nums == nil {
return []int{target}
}
var result []int // make slice to return
x := FindPosition(nums, target) //find where target belongs in slice
for i := range nums {
if i == x {
result = append(result, target)
}
result = append(result, nums[i])
}
return result
}
// returns what indices the element should be placed in to keep the slice sorted
func FindPosition(nums []int, target int) int {
for i := range nums {
if target == nums[i] {
return i
} else if target < nums[i] {
return i
}
}
return len(nums)
}
func VerifyBinary(nums []int)bool{
var temp int
for i := range nums {
temp = i +1
if nums[i] > temp {
return false
}
}
return true
}
// returns the index of the target element in the slice, if available or -1 if not
func BiSearch(nums []int, target int) int {
for i := range nums {
if target > nums[i] {
i ++
} else if target == nums[i] {
return i
} else if target < nums [i]{
if i > 0 {
i--
}
return -1
}
}
return -1
}