LINEAR SEARCH

LINEAR SEARCH

Why We Use Search ?
Now for example there is an array and we want to find the position of one element , we use linear search / binary search.

Example :

arr[] = {10, 20, 80, 30, 69, 50, 22, 18}
We want to find in which position 69 is present.
After Using a search we find the position of 69 is 4.

Logic Behind Linear Search :

  • Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
  • If x matches with an element, return the index.
  • Else Check the next element unless the array ends
#include<iostream>
using namespace std;
int main() {
	cout<<"Enter The Size Of Array:   ";
	int size;
	cin>>size;
	int array[size], key,i;
	// Taking Input In Array
	for (int j=0;j<size;j++) {
		cout<<"Enter "<<j<<" Element: ";
		cin>>array[j];
	}
	//Your Entered Array Is
	for (int a=0;a<size;a++) {
		cout<<"array[ "<<a<<" ]  =  ";
		cout<<array[a]<<endl;
	}
	cout<<"Enter Key To Search  in Array";
	cin>>key;
	for (i=0;i<size;i++) {
		if(key==array[i]) {
			cout<<"Key Found At Index Number :  "<<i<<endl;
			break;
		}
	}
	if(i != size) {
		cout<<"KEY FOUND at index :  "<<i;
	} else {
		cout<<"KEY NOT FOUND in Array  ";
	}
	return 0;
}

 

 

Discussion
best platform

1

Great platform 🙂🙂🙂🙂

2

Great Bro Helps me a lot Thanks

2

21

3