Home  >  Article  >  Backend Development  >  Binary search in sort package

Binary search in sort package

WBOY
WBOYforward
2024-02-09 12:24:09896browse

sort 包中的二分查找

php editor Strawberry will introduce you to the binary search algorithm in the sort package in this article. Binary search is an efficient search algorithm that is suitable for finding specific elements in ordered arrays. By continuously dividing the array into two parts and comparing it to the target element, we can quickly determine the position of the target element. The time complexity of this algorithm is O(log n), which is more efficient than linear search. In this article, we will explain in detail the implementation principles and steps of the binary search algorithm to help everyone better understand and apply this algorithm.

Question content

I am looking at this function "func SearchInts(a []int, x int) int in the Go sort package, and Curious if there is a direct way to identify if an element is present in a slice?

In Java Arrays.binarySearch(..), only negative values ​​are returned. I'm curious if golang's api func SearchInts(a []int, x int) reports that x does not exist? I don’t know why func SearchInts(a []int, x int) does not return two values ​​(index,isPresent)?

Solution

You can simply check:

i := sort.SearchInts(slice, value)
if i<len(slice) && slice[i]==value {
   // It exists
}

The above is the detailed content of Binary search in sort package. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete