This document contains code and explanations for linear search and binary search algorithms. It begins with an example of linear search on an array of numbers to find the position of the number 2. It then shows the C code for linear search. Next, it explains binary search with an example of finding the number 36 in a sorted array. It provides pseudocode and the C code implementation of binary search. It ends with an example run of the binary search code to find the number 67 in a sorted array of numbers.
3. Name :
Ms. Rifat Ara Shams
Designation :
Senior Lecturer
Department :
Department of
Computer Science and
Engineering
E-mail :
rifat.cse@diu.edu.bd
Cell-Phone :
+880-1723256560
6. LINEAR SEARCH
10 46 8 996 2 34 19578
ENTER THE ARRAY ELEMENTS
ENTER THE NUMBER TO BE SEARCHED
2
M[0] M[1] M[2] M[3] M[4] M[5] M[6] M{7] M[8] M[9]
7. LINEAR SEARCH
10 46 8 996 2 34 19578
2 2 2 2 2 2
THE NUMBER IS FOUND IN THE 6TH
POSITION
8. #include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in
arrayn");
scanf("%d",&n);
printf("Enter %d integer(s)n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
CODE
9. printf("Enter the number to searchn");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* if required
element found */
{
printf("%d is present at location
%d.n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.n",
search);
return 0;
}
10.
11. BINARY SEARCH
1 5 8 2412 36 48 876754
ENTER THE ARRAY ELEMENTS
ENTER THE NUMBER TO BE SEARCHED
36
M[0] M[1] M[2] M[3] M[4] M[5] M[6] M{7] M[8] M[9]
12. BINARY SEARCH
1 5 8 2412 36 48 876754
ENTER THE ARRAY ELEMENTS
ENTER THE NUMBER TO BE SEARCHED 36
M[0] M[1] M[2] M[3] M[4] M[5] M[6] M{7] M[8] M[9]
LB UB
19. Enter the elements of the array in ascending order
12
Enter the elements of the array in ascending order
23
Enter the elements of the array in ascending order
34
Enter the elements of the array in ascending order
45
Enter the elements of the array in ascending order
56
Enter the elements of the array in ascending order
67
Enter the elements of the array in ascending order
78
Enter the elements of the array in ascending order
89
Enter the elements of the array in ascending order
98
Enter the elements of the array in ascending order
100
Enter the number to be searched
67
found