Created
February 25, 2019 17:39
-
-
Save ndkhoa/f4eeac4be63ad5a51d39ca4cfbcab0fb to your computer and use it in GitHub Desktop.
binary search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import "fmt" | |
| func BinarySearch(array []int, element int) int { | |
| low := 0 | |
| high := len(array) - 1 | |
| for low <= high { | |
| index := (high + low) / 2 | |
| if element == array[index] { | |
| return index | |
| } | |
| if element < array[index] { | |
| high = index - 1 | |
| } else { | |
| low = index + 1 | |
| } | |
| } | |
| return -1 | |
| } | |
| func ResultMessage(got int, expected int) { | |
| if got != expected { | |
| fmt.Printf("Incorrect, got: %d, expected: %d.\n", got, expected) | |
| } else { | |
| fmt.Printf("Correct, got: %d, expected: %d.\n", got, expected) | |
| } | |
| } | |
| func TestBinarySearch(array []int, element int, expected int) { | |
| got := BinarySearch(array, element) | |
| ResultMessage(got, expected) | |
| } | |
| func main() { | |
| TestBinarySearch([]int{1, 2, 3}, 2, 1) | |
| TestBinarySearch([]int{1, 2, 3, 4}, 2, 1) | |
| TestBinarySearch([]int{1, 2, 3, 4, 5}, 2, 1) | |
| TestBinarySearch([]int{1, 2, 3, 4, 5}, 4, 3) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def binary_search(array, element) | |
| low, high = 0, array.size - 1 | |
| while low <= high | |
| index = (high + low)/2 | |
| return index if element == array[index] | |
| if element < array[index] | |
| high = index - 1 | |
| else | |
| low = index + 1 | |
| end | |
| end | |
| return -1 | |
| end | |
| puts binary_search([1,2,3], 2) | |
| puts binary_search([1,2,3,4], 2) | |
| puts binary_search([1,2,3,4,5], 2) | |
| puts binary_search([1,2,3,4,5], 4) | |
| puts binary_search([1,2,3,4,5], 0) | |
| def find_second_element(array, element) | |
| index = binary_search(array, element) | |
| return -1 if index == -1 | |
| if array[index - 1] == element | |
| while array[index - 1] == element | |
| index = index - 1 | |
| end | |
| return index + 1 | |
| end | |
| return index + 1 if array[index + 1] == element | |
| return -1 | |
| end | |
| puts find_second_element([1,2,2,2,5], 0) | |
| puts find_second_element([1,2,5], 2) | |
| puts find_second_element([1,2,2,5], 2) | |
| puts find_second_element([1,2,2,2,2,2,5], 2) | |
| puts find_second_element([1,1,1,1,2,2,5], 2) | |
| puts find_second_element([1,1,1,1,2,2,2,2,5], 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment