Go अभ्यास

Binary Search in Go

Find a value in a sorted slice by halving the search range at every step.

  • शुरुआती
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • low, high and middle
  • Returning -1 when missing
  • Why it is fast
Search for 23
20
82
164
235
386
567
Found at index 5 after three steps.

Halve the range each step

Binary search looks at the middle of a sorted list and throws away the half that cannot contain the target. Each step halves the work, so it is very fast on large lists.

low and high mark the part that is still being searched. The function returns the position of the target, or -1 when the range becomes empty. low + (high-low)/2 finds the middle without overflow.

मुख्य बातें

  1. The slice must be sorted.
  2. Each step throws away half.
  3. -1 means the value is not there.

चलने योग्य Go उदाहरण

Go
कोड चलाएँ →
main.go
package main

import "fmt"

func binarySearch(items []int, target int) int {
	low, high := 0, len(items)
	for low < high {
		middle := low + (high-low)/2
		switch {
		case items[middle] == target:
			return middle
		case items[middle] < target:
			low = middle + 1
		default:
			high = middle
		}
	}
	return -1
}

func main() {
	sorted := []int{2, 5, 8, 12, 16, 23, 38, 56}
	fmt.Println(binarySearch(sorted, 23))
	fmt.Println(binarySearch(sorted, 7))
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
5
-1

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Bank Account with Errors →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज