
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Explain Binary search in C language
Binary search method can be applied only to sorted list. The given list is divided into two equal parts. In the list, the key is compared with middle element.
Three situations may occur in binary search which are as follows −
If the middle element matches the key, then the search will end successfully here
If the middle element is greater than the key, then the search will proceed in the left partition
If the middle element is lower than the key, then the search will proceed in the right partition.
Input (i/p)
sorted list of elements, key.
Output (o/p)
- Success − If key is found.
- Unsuccessful − Otherwise.
Example
Following is the C program for binary search method −
#include<stdio.h> int main(){ int a[50], n, i, key, flag = 0, low, mid, high; printf("enter the no: of elements:"); scanf ("%d",&n); printf("enter the elements:"); for(i=0; i<n; i++) scanf( "%d", &a[i]); printf("enter a key element:"); scanf ("%d", &key); low = 0; high = n-1; while (low<= high ){ mid = (low + high) /2; if (a[mid] == key){ flag = 1; break; } else { if (a[mid] > key) high = mid-1; else low = mid+1; } } if (flag == 1) printf ("search is successful"); else printf("search is unsuccessful"); return 0; }
Output
When the above program is executed, it produces the following result −
enter the no: of elements:5 enter the elements:23 45 57 89 90 enter a key element:45 search is successful
- Related Articles
- Explain Binary Search in Python
- Binary Search in C++
- Binary search in C#
- How to find minimum element in an array using binary search in C language?
- Binary Search in C++ program?
- Binary Search Tree - Search and Insertion Operations in C++
- Binary Search functions in C++ STL
- Binary Search Tree Iterator in C++
- Unique Binary Search Trees in C++
- Binary Search a String in C++
- Recover Binary Search Tree in C++
- Binary Tree to Binary Search Tree Conversion in C++
- Explain C tokens in C Language
- Unique Binary Search Trees II in C++
- Balance a Binary Search Tree in c++

Advertisements