Searching Program in C Language
What is Searching?
Searching is an operation or a technique that helps finds the place of a given element or value in the list. Any search is said to be successful or unsuccessful depending upon whether the element that is being searched is found or not. Some of the standard searching technique that is being followed in data structure is listed below:
- Linear Search or Sequential Search
- Binary Search
Linear Search
// Linear Search C program#include <stdio.h>
int main()
{
int array[100], search, i, n;
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter %d integer(s)\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (i = 0; i < n; i++)
{
if (array[i] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, i+1);
break;
}
}
if (i == n)
printf("%d is not present in array.\n", search);
getch();
return 0;
}
Binary Search
// C programming code for binary search
#include <stdio.h>
void main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to find\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 found at location %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);
getch();
}
Comments
Post a Comment