SHARE
TWEET

Untitled

a guest Mar 24th, 2019 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "sort"
  6. )
  7.  
  8.  
  9. func binarySearch(arr []float64, target float64) float64{
  10.     low := 0
  11.     high := len(arr) - 1
  12.  
  13.     if target < arr[0] {
  14.         return arr[0]
  15.     }
  16.  
  17.     if target > arr[len(arr) - 1] {
  18.         return arr[len(arr) - 1]
  19.     }
  20.  
  21.  
  22.     for low <= high{
  23.         middle := (low + high) / 2
  24.  
  25.         if arr[middle] < target{
  26.             low = middle + 1
  27.         }else if arr[middle] > target{
  28.             high = middle - 1
  29.         }else {
  30.             return target
  31.         }
  32.     }
  33.  
  34.     if arr[low] - target < target - arr[high]{
  35.         return arr[low]
  36.     }else{
  37.         return arr[high]
  38.     }
  39. }
  40.  
  41. func main() {
  42.     var kotok = []float64{1.26, 2.24, 3.21, 4.56, 100, 50}
  43.     sort.Float64s(kotok)
  44.  
  45.     fmt.Println(binarySearch(kotok, -100))
  46. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top