Home  >  Article  >  System Tutorial  >  Algorithm - Detailed explanation of binary search

Algorithm - Detailed explanation of binary search

WBOY
WBOYforward
2024-02-15 10:00:13380browse

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!

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