Website For Developers

Searching in C++



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 in C++

Process of Sequential Search

Example of Sequential search in C++

#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;
}

Output

Enter an integer value: 101
Required value is not found in the array.


Binary Search in C++

Example of binary search in C++

#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;
}

Output

Enter the value you want to find: 99
Value is found.