Input some elements in increasing order and write a function to search an element using binary search method.
#include <stdio.h>
#include <conio.h>
void main ( )
{
int arr[10], i, n, p;
clrscr ( );
printf("\n\n\n\t\t Input Elements in Increasing Order.\n\n\n");
for ( i = 0; i < 10; i++ )
{
printf("\n\t Enter a number for position [%d] :",i); scanf("%d",&arr[i]);
if ( i != 0 && arr[i] < arr[i-1] )
{
printf("\n\t PLEASE ENTER ELEMENTS IN INCREASING ORDER.");
i--;
}
}
clrscr ( );
printf("\n\n\n\t The array is..:");
for ( i = 0; i < 10; i++ )
{
printf("%d ",arr[i]);
}
printf("\n\n\t Enter an element to search..:"); scanf("%d",&n);
p = binsearch ( arr, n, 10 );
if ( p == -1 )
{
printf("\n\t Element not found.");
}
else
{
printf("\n\t Element found in position %d",p);
}
getch ( );
}
int binsearch ( int arr[], int n, int len )
{
int m, l = 0, u = len - 1;
while ( u >= l )
{
m = ( l + u ) / 2;
if ( arr[m] == n )
{
return m;
}
if ( arr[m] < n )
{
l = m + 1;
}
else
{
u = m - 1;
}
}
return -1;
}
Click here to contact us
#include <stdio.h>
#include <conio.h>
void main ( )
{
int arr[10], i, n, p;
clrscr ( );
printf("\n\n\n\t\t Input Elements in Increasing Order.\n\n\n");
for ( i = 0; i < 10; i++ )
{
printf("\n\t Enter a number for position [%d] :",i); scanf("%d",&arr[i]);
if ( i != 0 && arr[i] < arr[i-1] )
{
printf("\n\t PLEASE ENTER ELEMENTS IN INCREASING ORDER.");
i--;
}
}
clrscr ( );
printf("\n\n\n\t The array is..:");
for ( i = 0; i < 10; i++ )
{
printf("%d ",arr[i]);
}
printf("\n\n\t Enter an element to search..:"); scanf("%d",&n);
p = binsearch ( arr, n, 10 );
if ( p == -1 )
{
printf("\n\t Element not found.");
}
else
{
printf("\n\t Element found in position %d",p);
}
getch ( );
}
int binsearch ( int arr[], int n, int len )
{
int m, l = 0, u = len - 1;
while ( u >= l )
{
m = ( l + u ) / 2;
if ( arr[m] == n )
{
return m;
}
if ( arr[m] < n )
{
l = m + 1;
}
else
{
u = m - 1;
}
}
return -1;
}
Click here to contact us
No comments:
Post a Comment