Diese Frage kann auf verschiedene Weise gelöst werden, deshalb zeigen wir Ihnen die Lösung, die für uns die vollständigste Lösung ist.
Beispiel 1: Binäres Suchprogramm c++
#include usingnamespace std;// This program performs a binary search through an array, must be sorted to workintbinarySearch(int array[],int size,int value){int first =0,// First array element
last = size -1,// Last array element
middle,// Mid point of search
position =-1;// Position of search value bool found =false;// Flag while(!found && first <= last){
middle =(first + last)/2;// Calculate mid point if(array[middle]== value)// If value is found at mid {
found =true;
position = middle;}elseif(array[middle]> value)// If value is in lower half
last = middle -1;else
first = middle +1;// If value is in upper half }return position;}intmain(){constint size =5;// size initializationint array[size]={1,2,3,4,5};// declare array of size 10int value;// declare value to be searched forint result;// declare variable that will be returned after binary search
cout <<"What value would you like to search for? ";// prompt user to enter value
cin >> value;
result =binarySearch(array, size, value);if(result ==-1)// if value isn't found display this message
cout <<"Not foundn";else// If value is found, displays message
cout <<"Your value is in the array.n";return0;}
Beispiel 2: Binäre Suche in c++
#include usingnamespace std;intbinarySearch(int arr[],int p,int r,int num){if(p <= r){int mid =(p + r)/2;if(arr[mid]== num)return mid ;if(arr[mid]> num)returnbinarySearch(arr, p, mid-1, num);if(arr[mid]< num)returnbinarySearch(arr, mid+1, r, num);}return-1;}intmain(void){int arr[]={1,3,7,15,18,20,25,33,36,40};int n =sizeof(arr)/sizeof(arr[0]);int num =33;int index =binarySearch(arr,0, n-1, num);if(index ==-1)
cout<< num <<" is not present in the array";else
cout<< num <<" is present at index "<< index <<" in the array";return0;}
Beispiel 3: Binärer Suchbaum
Binary Search Tree is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
Beispiel 4: Binärer Suchbaum
#Driver Code
arr =[2,3,4,10,40]
x =10#Function call
result =binarySearch(arr,0,len(arr)-1, x)if result !=-1:print("Element is present at index % d"% result)else:print("Element is not present in array")
Posten Sie Kommentare und Bewertungen
Denken Sie daran, dass wir Ihnen das Privileg geben, zu erklären, ob es für Sie hilfreich war.