You are on page 1of 4

PROGRAM - 4

Write a program to implement binary search for iterative method.

PSEUDO CODE:

do until the pointers low and high meet each other. mid = (lowerbond + upperbond)/2
if (x == arr[mid]) return mid
else if (x > arr[mid]) // x is on the right side
lowerbond = mid + 1
else// x is on the left side upperbond = mid - 1

CODE :

#include <stdio.h>

int binarySearch(int array[], int x, int low, int high) {


// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;

if (array[mid] == x)
return mid;

if (array[mid] < x)
low = mid + 1;

else
high = mid - 1;
}

return -1;
}
int main(void) {
printf("Aditya Bhattacharya\n");
printf("A2305220431\n");
int array[] = {2, 3, 4, 6 , 8, 10};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}
OUTPUT:

COMPLEXITY: O(log N) (1)


PROGRAM – 4A

Write a program
PSEUDO CODE: to implement binary search for Recursive Method.

binarySearch(arr, x, low,
CODE :
high) if low > high
return
False else
#include
mid =<stdio.h>
(low + high) /
2 if x == arr[mid]
return mid
int binarySearch(int array[], int x, int low, int high) {
else if x >
if (high >= low) { arr[mid] // x is on the right
intside
midreturn
= lowbinarySearch(arr, x, mid + 1,
+ (high - low) / 2;
high)
else // x is on the right
// Ifside
found at mid, then return
return binarySearch(arr, it mid -
x, low,
if (array[mid] == x)
return mid;

// Search the left half


if (array[mid] > x)
return binarySearch(array, x, low, mid - 1);

// Search the right half


return binarySearch(array, x, mid + 1, high);
}

return -1;
}

int main(void) {
printf("Aditya Bhattacharya\n");
printf("A2305220431\n");
int array[] = {2,3,4,6,8,10};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
}

OUTPUT:
TIME COMPLEXITIES:
 Best case complexity: O(1)
 Average case complexity: O(log n)
 Worst case complexity: O(log n)

You might also like