Binary Search, Binary Search Algorithm
Binary Search, also known as semi-query, has the advantage of a small number of times, fast query speed, and good average performance. Its disadvantage is that the table to be queried is an ordered table and it is difficult to insert or delete data.
Assume that the array length is n, and the algorithm complexity is o (log (n ))
Code:
#include <iostream>using namespace std;bool BinarySearch(int data[],int start, int end, int number){while(start <= end){int mid=(start + end ) / 2;if(data[mid] == number){return true;}if(data[mid] > number){end = mid - 1;}else{start = mid + 1;}}return false;}int main(){int input[9]={0,1,1,1,3,4,5,6,7}; cout<<BinarySearch(input,0,8,8);return 0;}
Running result:
Binary Search Algorithm
Prerequisites: data must be sorted with recursive and non-recursive versions.
Int binSearch (const int * Array, int start, int end, int key)
{
Int left, right;
Int mid;
Left = start;
Right = end;
While (left <= right) {/recursive algorithm in comments. The execution efficiency is low and is not recommended.
Mid = (left + right)/2;
/* If (key <Array [mid]) {
Return (binSearch (Array, left, mid, key ));
}
Else if (key> Array [mid]) {
Return (binSearch (Array, mid + 1, right, key ));
}
Else
Return mid;
*/
If (key <Array [mid]) {
Right = mid-1;
}
Else if (key> Array [mid]) {
Left = mid + 1;
}
Else
Return mid;
}
Return-1;
}
Binary Search Algorithm
Prerequisites: data must be sorted with recursive and non-recursive versions.
Int binSearch (const int * Array, int start, int end, int key)
{
Int left, right;
Int mid;
Left = start;
Right = end;
While (left <= right) {/recursive algorithm in comments. The execution efficiency is low and is not recommended.
Mid = (left + right)/2;
/* If (key <Array [mid]) {
Return (binSearch (Array, left, mid, key ));
}
Else if (key> Array [mid]) {
Return (binSearch (Array, mid + 1, right, key ));
}
Else
Return mid;
*/
If (key <Array [mid]) {
Right = mid-1;
}
Else if (key> Array [mid]) {
Left = mid + 1;
}
Else
Return mid;
}
Return-1;
}