In a linear search, you iterate through each element of an array until you find the target element or reach the end of the array. In the case of a sorted array, you can optimize the search process by stopping the search when you find an element greater than the target, as it implies the target won’t be found in the remaining elements.
Here’s a simple example of a C program for linear search in a sorted array
Program :
#include <stdio.h>
#include <conio.h>
Â
void main( )
{
int arr[10];
int i,n,num ;
printf(“Enter the number of Elements : “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Element%d : “,i+1);
scanf(“%d”,&arr[i]);
}
printf ( “Enter number to search: ” ) ;
scanf ( “%d”, &num ) ;
Â
for ( i = 1 ; i <= n ; i++ )
{
if ( arr[n] < num || arr[i] >= num )
{
if ( arr[i] == num )
printf ( “The number is at position %d in the array.”, i ) ;
else
printf ( “Number is not present in the array.” ) ;
break ;
}
}
Â
getch( ) ;
}