Home > System Tutorial > LINUX > body text

Algorithm - Detailed explanation of binary search

WBOY
Release: 2024-02-15 10:00:13
forward
380 people have browsed it

Algorithm - Detailed explanation of binary search

Binary search is also called half search, Advantages are less number of comparisons, fast search speed, good average performance, and takes up less system memory;

The disadvantage is that the table to be looked up is required to be an ordered table, and insertion and deletion are difficult.

Therefore, the half search method is suitable for ordered lists that do not change frequently but are searched frequently .

First, assuming that the elements in the table are arranged in ascending order, compare the keyword recorded in the middle of the table with the search keyword. If the two are equal, the search is successful;

Otherwise, use the middle position record to divide the table into the first and last sub-tables. If the keyword of the middle position record is greater than the search keyword, then further search the former sub-table, otherwise further search the latter sub-table.

Repeat the above process until a record that meets the conditions is found, making the search successful, or until the subtable does not exist, in which case the search fails.

#include <iostream><br> using namespace std;</iostream>

int binary_search(int *A,int n,int key)
{
int left=0,right=n-1;
while(left>1;
if(key==A[mid])
return mid;
else if(key>key;
cout

The above is the detailed content of Algorithm - Detailed explanation of binary search. For more information, please follow other related articles on the PHP Chinese website!

source:linuxprobe.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!