Binary search or half-interval search algorithm compares the
element to be search(i.e key) with the middle element of the array.
If the key is matched with the middle element ,it returns its
position.and if not it divides the array into sub array according to
the value of key.
If the key value is greater than the value of middle element then
the it will search the key from middle to right.
If the key value is less than the value of middle element then the it
will search the key from middle to left.
It will repeat this action until no further division are possible or
until the key matches with any of the element in array.
Binary search Binary search
/*....binary search program ......*/
#include <stdio.h>
void main()
{
int arr[20];
int i, low, mid, high, key, size;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the elements\n");
for(i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the element to be search according to binary search\n");
scanf("%d", &key);
/*Binary search */
low = 0;
high = (size - 1);
while(low <= high)
{
mid = (low + high)/2;
if(key == arr[mid])
{
printf("element found at %d position \n",mid+1);
return;
}
if(key < table[mid])
high = mid - 1;
else
low = mid + 1;
}
printf("element not found\n");
getch();
}
Binary search Binary search Binary search Binary search
Output
Enter the size of an array
5
Enter the array elements
12
36
45
78
99
Enter the key
45
element found at 3 position
Monday, 29 July 2013
Home »
C language
» Algorithm and program for Binary Search.
Algorithm and program for Binary Search.
Related Posts:
How to print Hello with out using ;(semi-colon)? This can be done using following ways: 1.#include<stdio.h> void main(){ if(printf("Hello world")){ } } 2.#include<stdio.h> void main(){ … Read More
Difference between Declaring a variable , Defining a variable ,Internal static variable and External static variable Declaring a variable Declaring a variable means describing its type (data type) but not allocating any space for it. Defining a variable: Defining a variable means declaring it and also allocating space to hold… Read More
Difference between Malloc and Calloc 1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to Zero. The total number of memory allocated will be (number_of_elements * &… Read More
What is the difference between String and Character Array? String have static storage duration, While character array not, unless it is specified by using the static keyword. Moreover a string is a character array having properties: the sequence of character, g… Read More
What are the different storage classes in C ? A storage class defines the scope and life time of variables. There are four storage classes: Auto Storage class Register Storage class Static Storage class Extern Storage class 1.auto - Storage Cla… Read More
0 comments:
Post a Comment