Binary Search CPP Algorithm

C Program for Binary Search Algorithm

A binary search is a dichotomic divide and conquer search algorithm. Binary search algorithm locates the position of an item in a sorted array. Binary search works by comparing an input value to the middle element of the array. The comparison determines whether the element equals the input, less than the input or greater. When the element being compared to equals the input the search stops and typically returns the position of the element. The below function written in C can help you to perform the Binary Search

Binary Serach


#include <stdio.h>
#include <stdlib.h>
int binary_search(int data[],int search_item,int length)
{
int min =-1;
int max = length;
while(true)
{
// found condition.
if(data[(min+max)/2]==search_item)
return (min+max)/2;
// termination condition.
if(min==max)
{
return -1;
}
// else
if(data[(min+max)/2]<search_item)
{
min=(min+max)/2;
}
else{
max=(min+max)/2;
}

}
}


int main()
{
#define MAX_ARRAY_SIZE 100
// an array to binary_search.
int int_array[MAX_ARRAY_SIZE];

// fill this array from the stdin.
int count=0;
printf("please enter the numbers you want to sort -1 to end:
");
while(true)
{
int input;
scanf("%i",&input);

if(input==-1)
break;
else
int_array[count]=input;
if(count>=MAX_ARRAY_SIZE)
exit(0);
count++;
}

// get the value that you need to search.
int search;
printf("Plese enter the value that you need to Search");
scanf("%i",&search);

// search.
int result;
if((result=binary_search(int_array,search,count))==-1)
{
printf("the value %i does not found in the array
",search);
}else{
printf("the value %i is located at index %i
",search,result);
}

return 0;
}


Related Topic C program to perform Binary search
List of Mysql Error Code and Description
inArray Method
List of Encryption in MySQL
8 Queens Problem Backtracking Algorithm and Java Program

nScraps.com 2011   Privacy Policy  Terms of Service  Feedback