Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Lab # 4

IMPLEMENT LINEAR AND BINARY SEARCH


Task 1:

Write a function to create an array.


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.
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.
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+l); 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:
From this lab, I learned the programming and implementation of linear search and
binary search in an array. I also became able to know about the working of each
searching type step by step.

You might also like