Skip to content

Commit

Permalink
linear_search and binary_search
Browse files Browse the repository at this point in the history
* linear_search_c++.cpp created

* binary_search_c++.cpp created
  • Loading branch information
ambujraj2001 authored Dec 8, 2021
1 parent 8914f09 commit fd4730a
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
39 changes: 39 additions & 0 deletions 6_Searching/binary_search_c++.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <bits/stdc++.h>
using namespace std;

void binary_search(int ar[], int n, int x) // fucntion for binary search with three parametes as array,size of array,no to be searched
{
int l = 0;
int r = n - 1;
while (l <= r)
{
int m = l + (r - l) / 2;

// Check if x is present at mid
if (ar[m] == x)
{
cout << "Element is Present in the Array at index: " << m << "\n";
return;
}

// If x greater, ignore left half
if (ar[m] < x)
l = m + 1;

// If x is smaller, ignore right half
else
r = m - 1;
}
cout << "Element is not Present in the Array\n"; // if element is not present in the array
}

int main() // main method
{
int arr[5] = {8, 16, 4, 78, 44}; // Creating an array of size 5
int to_be_searched = 78; // the number to be searched
binary_search(arr, 5, to_be_searched); // function call for binary search

int arr1[5] = {18, 6, 41, 8, 21}; // Creating an array of size 5
int to_be_searched1 = 2; // the number to be searched
binary_search(arr1, 5, to_be_searched1); // function call for binary search
}
37 changes: 37 additions & 0 deletions 6_Searching/linear_search_c++.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <bits/stdc++.h>
using namespace std;

void linear_search(int ar[], int n, int x) // fucntion for linear search with three parametes as array,size of array,no to be searched
{
int found = 0; // flag variable
int index = -1;
for (int i = 0; i < n; i++)
{
if (ar[i] == x) // checking if element is equal to the no to be searched
{
found = 1; // updating the flag
index = i; // storing the index of the element found
break; // since the element is found therefore no need to traverse further thus exiting the loop
}
}

if (found == 1) // if element is present in the array then flag status is 1
{
cout << "Element is Present in the Array at index: "<<index<<"\n";
}
else
{
cout << "Element is not Present in the Array\n";
}
}

int main() // main method
{
int arr[5] = {8, 16, 4, 78, 2}; // Creating an array of size 5
int to_be_searched = 2; // the number to be searched
linear_search(arr, 5, to_be_searched); // function call for linear search

int arr1[5] = {18, 6, 41, 8, 21}; // Creating an array of size 5
int to_be_searched1 = 2; // the number to be searched
linear_search(arr1, 5, to_be_searched1); // function call for linear search
}

0 comments on commit fd4730a

Please sign in to comment.