Simple Binary Searching Program using functions in C
Definition:
Binary search is a quickest search algorithm that finds the position of a target value within a sorted array
Also Called,
- half-interval search
- logarithmic search
- binary chop
Simple Binary Searching Program using functions
/* Simple Binary Search Program Using Functions in C*/
/* Data Structure Programs,C Array Examples */
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 5
void binary_search(int[],int);
int main() {
int arr_search[MAX_SIZE], i,element;
printf("Simple Binary Search Example - Array and Functions\n");
printf("\nEnter %d Elements for Searching : \n", MAX_SIZE);
for (i = 0; i < MAX_SIZE; i++)
scanf("%d", &arr_search[i]);
printf("Enter Element to Search : ");
scanf("%d", &element);
binary_search(arr_search,element);
getch();
}
void binary_search(int fn_arr[],int element) {
int f = 0, r = MAX_SIZE,mid;
while (f <= r) {
mid = (f+r)/2;
if (fn_arr[mid] == element) {
printf("\nSearch Element : %d : Found : Position : %d.\n", element, mid+1);
break;
}
else if (fn_arr[mid] < element)
f = mid + 1;
else
r = mid - 1;
}
if (f > r)
printf("\nSearch Element : %d : Not Found \n", element);
}
Sample Output
Simple Binary Search Example - Array and Functions
Enter 5 Elements for Searching :
1001
1020
3002
4001
5000
Enter Element to Search : 3002
Search Element : 3002 : Found : Position : 3.
Read More Articles
- Use of getch(),getche() and getchar() in C
- Switch Case Statement Example Program In C Programming Language
- C Character Set
- Convert a Floating-point value to an Integer in C
- Data Input and Output gets and puts Example Program In C
- Special Operators In C
- Pointer Representation and Pointer Example Programs
- C Data Input and Data Output
- Simple While Loop Example Program In C Programming Language
- Data Output printf and putchar Example Program In C
- C Introduction
- C Operators
- Storage Classes In C
- C Pointers
- File Management
- C Identifiers
- Loop Control Statements
- Hello World - Simple C Program
- C Array
- Single Character Output Function : putchar()
- C Reserve Words
- C Specific Properties and Implementation
- If else Statement Example Program In C Programming Language
- If Statement Example Program In C Programming Language
- Confusing Array in C ( Array Representation and Initialization )