Searching in C++ is the process of finding required data in the array.

Searching is very useful when the size of array is large.

Let see the two techniques / algorithms of searching in C++.

- Sequential Search
- Binary Search

- Sequential search in C++ is a very simple technique of searching.
- Sequential search called linear search or serial search.
- In sequential search, every element in the array compared with required value one by one.

- First, cursor visits the first value of an array and compared it with the required value.
- If the required value matches on very first index, search is complete.
- If value does not match, cursor moves to the next element and repeat same process.
- For the purpose of visiting array loops are frequently used.

#include<iostream>

#include<conio.h>

using namespace std;

int main() {

int array[5] = {54, 89, 31, 14, 150};

int check = -1;

int value;

cout<<"Enter an integer value: ";

cin>>value;

for (int i = 0; i < 5; i++) {

if (array[i] == value) {

check = i;

}

}

if (check == -1) {

cout<<"Required value is not found in the array. ";

}

else {

cout<<"Required value is found. ";

}

getch();

return 0;

}

Enter an integer value: 101

Required value is not found in the array.

- Binary search is a fast technique of searching in C++.
- It works only if the array is sorted.
- It starts from middle value of the array.
- If the middle element and the search number are same then the search is successful and the index of the middle element is returned.
- If the search number is less than the middle element, it starts searching the first half of array and leaves the second half.
- If the search number is greater than the middle element, it starts searching the second half of array and leaves the second half.
- This procedure will continue until we find the valueor loop completes without successful search.

#include<iostream>

#include<conio.h>

using namespace std;

int main() {

int array[] = {10, 22, 31, 35, 48, 99};

int value, mid, check = -1, first = 0, last = 6;

cout<<"Enter the value you want to find: ";

cin>>value;

while (first <= last) {

mid = (first + last) /2;

if (array[mid] == value) {

check = mid;

break;

}

else if (value < array[mid]) {

last = mid - 1;

}

else {

first = mid + 1;

}

}

if (check == -1){

cout<<"Value is not found in the array. ";

}

else {

cout<<"Value is found. ";

}

getch();

return 0;

}

Enter the value you want to find: 99

Value is found.