Write a C program that uses non recursive function to search for a Key value in a given sorted list of integers using Binary search.
Algorithm:
Step 1: Start
Step 2: Initialize
low = 1
high = n
Step 3: Perform Search
While(low <= high)
Step 4: Obtain index of midpoint of interval
Middle = (low + high) / 2
Step 5: Compare
if(X < K[middle])
high = middle - 1
else
print “Element found at position”
Return(middle)
goto: step 2
Step 6: Unsuccessful Search
print “Element found at position”
Return (middle)
Step 7: Stop
Flowchart:

Program:
#include<stdio.h> #include<conio.h> void main() { int a[20], i, n, key, low, high, mid; clrscr(); printf(“Enter the array elements in ascending order”); for(i = 0; i < n; i++) { scanf(“%d”, &a[i]); } printf(“Enter the key element\n”); scanf(“%d”, &key); low = 0; high = n - 1; while(high >= low) { mid = (low + high) / 2; if(key == a[mid]) break; else { if(key > a[mid]) low = mid + 1; else high = mid - 1; } } if(key == a[mid]) printf(“The key element is found at location %d”, mid + 1); else printf(“the key element is not found”); getch(); }
Input & Output:
Enter the size of the array 7 Enter the array elements in ascending order 23 45 68 90 100 789 890 Enter the key element 789 The key Element is found at location 6
-
UpdatedOct 21, 2014
-
Views50,935
You May Like
Write a C program to find the roots of a quadratic equation.
Write a C program to count the lines, words and characters in a given text.
Write a C program, which takes two integer operands and one operator from the user, performs the operation and then prints the result. (Consider the operators +,-,*, /, % and use switch statement)
Write a C program to find the sum of individual digits of a positive integer.
Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by the user.
Write C programs that use both recursive and non-recursive functions
- To find the
factorialof a given integer. - To find the
GCD(greatest common divisor) of two given integers.