You are on page 1of 3

NFC Institute of Engineering&Fertilizer

Research Faisalabad

Department of Electrical Engineering


Fourth Semester
Course Title:
Data Structure & Algorithms (EE-232)
Topic:
Lab Assignments
Submitted To:
Dr. Salman Arain
Submitted By:
Hafeez Ali
Roll.No:
18-ELE-43
Reg.#:
2018-UET-NFC-FD-ELECT-43
Lab.No.4
IMPLEMENT LINEAR AND BINARY SEARCH
Task#1
Write a function to create an array.
C Function:
int createArray( arraySize )
{
Int i, n[ arraySize ];
printf("Enter %d integers: ", arraySize);

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


scanf("%d", &n[i]);
}
}

Task#2
Write a function to perform a linear search on an array.
C Function:
int linear_search(int *array, int n)
{
int c, search;
printf("Enter the number to search\n");
scanf("%d", &search);

for ( c = 0 ; c < n ; c++ ){


if ( *(array+c) == search ){
printf("Element is present in the array\n");
}
}
}
Task#3
Write a function to perform a binary search on an array.
C Function:
int binary_search(int *array, int n)
{
int c, first, last, middle, search;
printf("Enter the number to search\n");
scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
printf("%d is present at index %d.\n", search, middle+1);
break;
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last) {
printf("Not found! %d is not present in the list.\n", search);
}
}

Conclusion:
In this lab, I came to know the programming and implementation of linear
search and binary search in an array. I also came to know the working of each searching type
step by step.

You might also like