Lecture 8
Lecture 8
Algorithm
LinearSearch(array, key)
for each item in the array
if item == value
return its index
Linear Search
Linear Search
Implementation
Recursive Method
do until the pointers low and high meet each other. if low > high
if (x == arr[mid]) else
else // x is on the left side else if x > arr[mid] // x is on the right side
#include <stdio.h>
int main(void) {
int binarySearch(int array[], int x, int low, int high) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
if (high >= low) {
int n = sizeof(array) / sizeof(array[0]);
int mid = low + (high - low) / 2;
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
// If found at mid, then return it
if (result == -1)
if (array[mid] == x)
printf("Not found");
return mid;
else
printf("Element is found at index %d", result);
// Search the left half
}
if (array[mid] > x)
return binarySearch(array, x, low, mid - 1);