• October 27, 2021

PHSARIT

Bring Technology Ideas with you

 Function Search in C++: Linear/Sequential Search and Binary Search in Data Structure with C++

Search Algorithm is one of the technique which can be used for target items in the collection of data. Those can be applied as the determine of the average number of comparisons in the successful case and consider all possible cases. There are some coding of the search techniques which can be written:

#include<iostream>
using namespace std;

// Function to use Linear Search
int Sqsearch(int arr[], int size, int searchKey)
{
	for (int i = 0; i < size; i++) //loop/traverse in the list
	{
if (searchKey == arr[i])
{
	return i; //search found
} 
}
return -1; //not found
}
// binary search function
int Bsearch(int arr[], int size, int searchKey)
{
	int low = 0;
	int high = size - 1;
	int middle;
	while (low<=high)
	{
		middle = (low + high) / 2;
		if (searchKey == arr[middle])
		{
			return middle;
		}
		else if(searchKey>arr[middle])
		{
			low = middle + 1;
		}
		else
		{
			high = middle - 1;
		}
	}
	return -1;
 }

int main()
{
	//int arr[] = {23,45,3,4,7,12,8,90,100};
	int arr[] = { 3,4,7,8,12,23,45,90,100 };
	int search;
	cout << "Enter number to search in the list: ";
	cin >> search;
	int result = Bsearch(arr, 9, search); // call binary search as example
	if (result >=0)
	{
		cout <<"Great result, the number found "<<arr[result]<<" at index: "<<result<<endl;
	}
	else
	{
		cout << "The number was not found!"<< endl;
	}
	system("pause==0");
}

Related post