Binary search in sort package

WBOY
Release: 2024-02-09 12:24:09
forward
896 people have browsed it

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!