Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views3 pages

Linear Search and Binary Search

The document provides C code implementations for linear and binary search algorithms. Linear search iterates through an array to find a specified key, while binary search requires a sorted array and divides the search space in half to locate the key. The main function allows user input for the number of elements and the elements themselves, then performs both search algorithms and displays the results.

Uploaded by

Sunzz
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)
5 views3 pages

Linear Search and Binary Search

The document provides C code implementations for linear and binary search algorithms. Linear search iterates through an array to find a specified key, while binary search requires a sorted array and divides the search space in half to locate the key. The main function allows user input for the number of elements and the elements themselves, then performs both search algorithms and displays the results.

Uploaded by

Sunzz
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/ 3

IMPLEMENT LINEAR SEARCH AND BINARY SEARCH

ALGORITHMS

#include <stdio.h>
// Linear Search
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // return index if found
}
}
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;
}
else if (arr[mid] < key) {
low = mid + 1; // search right half
}
else {
high = mid - 1; // search left half
}
}
return -1; // not found
}

int main() {
int n, key;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements (in sorted order for Binary Search):\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter element to search: ");
scanf("%d", &key);

// Linear Search
int linearResult = linearSearch(arr, n, key);
if (linearResult != -1)
printf("Linear Search: %d found at index %d\n", key, linearResult);
else
printf("Linear Search: %d not found\n", key);

// Binary Search
int binaryResult = binarySearch(arr, n, key);
if (binaryResult != -1)
printf("Binary Search: %d found at index %d\n", key, binaryResult);
else
printf("Binary Search: %d not found\n", key);
return 0;
}

You might also like