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

searching algorithm Q2

The document contains C++ code implementing two search algorithms: linear search and binary search. The linear search function iterates through an array to find a specified key, while the binary search function requires a sorted array and uses a divide-and-conquer approach. The main function demonstrates both search methods on a predefined sorted array, outputting the index of the found key or indicating if it was not found.

Uploaded by

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

searching algorithm Q2

The document contains C++ code implementing two search algorithms: linear search and binary search. The linear search function iterates through an array to find a specified key, while the binary search function requires a sorted array and uses a divide-and-conquer approach. The main function demonstrates both search methods on a predefined sorted array, outputting the index of the found key or indicating if it was not found.

Uploaded by

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

#include <iostream>

using namespace std;

// Linear Search

int linearSearch(int arr[], int n, int key) {

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

if (arr[i] == key)

return i; // found at index i

return -1; // not found

// Binary Search (array must be sorted)

int binarySearch(int arr[], int n, int key) {

int low = 0, high = n - 1;

while (low <= high) {

int mid = (low + high) / 2;

if (arr[mid] == key)

return mid; // found

else if (arr[mid] < key)

low = mid + 1;

else

high = mid - 1;

return -1; // not found

}
int main() {

int arr[] = {5, 10, 15, 20, 25, 30}; // sorted array

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

int key = 25;

// Linear Search

int linResult = linearSearch(arr, n, key);

if (linResult != -1)

cout << "Linear Search: Found at index " << linResult << endl;

else

cout << "Linear Search: Not found\n";

// Binary Search

int binResult = binarySearch(arr, n, key);

if (binResult != -1)

cout << "Binary Search: Found at index " << binResult << endl;

else

cout << "Binary Search: Not found\n";

return 0;

You might also like