0% found this document useful (0 votes)
17 views

searching code

The document contains implementations of linear and binary search algorithms in C++. The linear search function iterates through an array to find a specified element, while the binary search function efficiently finds an element in a sorted array by repeatedly dividing the search interval in half. Both implementations include driver code to demonstrate their functionality.

Uploaded by

alehegn admasu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

searching code

The document contains implementations of linear and binary search algorithms in C++. The linear search function iterates through an array to find a specified element, while the binary search function efficiently finds an element in a sorted array by repeatedly dividing the search interval in half. Both implementations include driver code to demonstrate their functionality.

Uploaded by

alehegn admasu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

 Linear search implementation

#include <iostream>

using namespace std;

int search(int arr[], int n,int data)

for (int i = 0; i < n; i++)

if (arr[i] == data){

return i;}

else{

return -1;

}}

// Driver code

int main(){

int arr[] = {2, 3, 4, 10, 40};

int data = 11;

int n = sizeof(arr) / sizeof(arr[0]);

// Function call

int result = search(arr, n, data);

if(result == -1) {

cout << "Element is not present in array" ; }

else

cout << "Element is present at index " << result;

return 0;

}
 Binary search implementation

#include <iostream>

using namespace std;

int binarySearch(int arr[], int left, int right, int key){

while (left <= right) {

int mid = left + (right - left) / 2;

// Check if key is present at mid

if (arr[mid] == key)

return mid;

// If key greater, ignore left half

if (arr[mid] < key)

left = mid + 1;

// If key is smaller, ignore right half

else right = mid - 1; }

// If we reach here, then element was not present

return -1;

int main(void)

int arr[] = { 2, 3, 4, 10, 40 };

int key= 2;

int n = sizeof(arr) / sizeof(arr[0]);

int result = binarySearch(arr, 0, n - 1, key);

if(result == -1){

cout << "Element is not present in array";


}

else{

cout << "Element is present at index " << result;}

return 0;

You might also like