0% found this document useful (0 votes)
17 views2 pages

JP2II

The document contains a C program that implements a binary search algorithm to find a specified value in a sorted array. It prompts the user to input the number of elements, the elements themselves, and the value to search for, then outputs whether the value is found and its location or indicates that it is not present. Additionally, it highlights a common pitfall of using binary search on an unsorted array with an example scenario.

Uploaded by

abhishekgkcorner
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views2 pages

JP2II

The document contains a C program that implements a binary search algorithm to find a specified value in a sorted array. It prompts the user to input the number of elements, the elements themselves, and the value to search for, then outputs whether the value is found and its location or indicates that it is not present. Additionally, it highlights a common pitfall of using binary search on an unsorted array with an example scenario.

Uploaded by

abhishekgkcorner
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

//Program Name: BinarySearch.c #include<stdio.

h>
int 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 ( c = 0 ; c < n ; c++ )
scanf("%d",&array[c]);
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);
return 0;
}

OUTPUT:
Scenario 1: Element Found Input:
Enter number of elements 5
Enter 5 integers
10
20
30
40
50
Enter value to find
30
Output:
Enter number of elements
5
Enter 5 integers
10
20
30
40
50
Enter value to find
30
30 found at location 3.

Scenario 2: Element Not Found Input:


Enter number of elements
Output:
Enter number of elements 5
Enter 5 integers
10
20
30
40
50
Enter value to find
25
Not found! 25 is not present in the list.

Scenario 3: Array not sorted (Illustrating a common pitfall)


* Input:
Enter number of elements
4
Enter 4 integers
50
10
40
20
Enter value to find
10

You might also like