(12). 8.2 Searching in Arrays. - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki

//LINEAR SEARCH //Find the index of key = 8 in {12 , 18 , 42 , 8 , 10} #include using namespace std;

int linearSearch(int arr[] , int n, int key){ for(int i=0;i<n;i++){ if(arr[i]==key){ return i; } } return -1; }

int main(){ int n; cout << "Enter the size of arrays: "; cin >> n;

int arr[n];
for(int i=0;i<n;i++){
	cin >> arr[i];
}

int key;
cout << "Enter the key: ";
cin >> key;

cout << linearSearch(arr,n,key) << endl;

return 0;

}

/* OUTPUT: Enter the size of arrays: 5 34 42 12 67 45 Enter the key: 12 2 */

//BINARY SEARCH //Find the index of key = 27 in {8,10,12,21,27,34,42} #include using namespace std;

int binarySearch(int arr[] , int n , int key){ int s=0; //s=start int e=n; //e=end while(s<=e){ int mid = (s+e)/2; if(arr[mid]==key){ return mid; } else if(arr[mid]>key){ e=mid-1; } else{ s=mid + 1; } } return -1; }

int main(){ int n; cout << "Enter the size of array: "; cin >> n;

int arr[n];
for(int i=0;i<n;i++){
	cin >> arr[i];
}

int key;
cout << "Enter the key: ";
cin >> key;

cout << binarySearch(arr,n,key) <<endl;

return 0;

}

/* OUTPUT: Enter the size of array: 5 10 20 30 40 50 Enter the key: 40 3 */

⚠️ **GitHub.com Fallback** ⚠️