INSTITUTE OF TECHNOLOGY & MANAGEMENT
Integrated Technical Campus: Engineering, Pharmacy & Management
Approved by AICTE, Pharmacy Council of India, New Delhi & Affiliated to Dr. APJAKTU,
AL-1, Sector - 7, GIDA, Gorakhpur - 273209 (UP)
Design and Analysis of Algorithm Lab (BCS553)
Practical-1
(a) Program for Recursive Linear Search.
#include <stdio.h>
int linearSearch(int arr[], int size, int key)
// If the size of the array is zero, return -1
if (size == 0) {
return -1;
if (arr[size - 1] == key) {
return size - 1;
return linearSearch(arr, size - 1, key);
int main()
int arr[] = { 5, 15, 6, 9, 4 };
int key = 4;
int index
= linearSearch(arr, sizeof(arr) / sizeof(int), key);
if (index == -1) {
printf("Key not found in the array.\n");
INSTITUTE OF TECHNOLOGY & MANAGEMENT
Integrated Technical Campus: Engineering, Pharmacy & Management
Approved by AICTE, Pharmacy Council of India, New Delhi & Affiliated to Dr. APJAKTU,
AL-1, Sector - 7, GIDA, Gorakhpur - 273209 (UP)
else {
printf("The element %d is found at %d index of the "
"given array \n",
key, index);
return 0;
➢ Output
The element 4 is found at 4 index of the given array.
(b) Program for Binary Search: -
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int x)
{
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
INSTITUTE OF TECHNOLOGY & MANAGEMENT
Integrated Technical Campus: Engineering, Pharmacy & Management
Approved by AICTE, Pharmacy Council of India, New Delhi & Affiliated to Dr. APJAKTU,
AL-1, Sector - 7, GIDA, Gorakhpur - 273209 (UP)
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = size of(arr) / size of (arr[0]);
int x = 10;
int result = binarySearch (arr, 0, n - 1, x);
if (result == -1) printf ("Element is not present in array");
else printf ("Element is present at index %d",result);
➢ Output: -
Element is present at index 3