Binary Search Using C Language


#include"stdio.h"
#include"conio.h"
int array[50],m=-1,n,size,key;
void displayArray();
void sortArray();
int binarySearch();
int main(){
clrscr();
printf(":BINARY SEARCH:\n");
printf(":=============:\n");
do
    {
m++;
printf("\n -1 EXIT\t");
printf("Pos: Array[%d] =",m);
scanf("%d",&array[m]);

}while(array[m]!=-1);
size=m;
printf("Enter value to be search...");
scanf("%d",&key);
//////////////////////////////////////////////
clrscr();
printf("\nDEMONSTRATING BINARY SEARCH (C index start from 0)\n");
printf("\n===========================\n");
printf("\nYOUR ENTERED DATA\n");
displayArray();
//////////////////////////////////////////////
printf("\n\nAFTER ASCENDING SORT\n");
sortArray();
displayArray();
printf("\n\nSEARCHING VALUE = %d\n",key);
int x=binarySearch();
printf("\n Valued Found at Index = %d",x);
getch();
return 0;
}
/////////////////////////////////////////////

void displayArray(){
for(int i=0;i
printf("%d\t",array[i]);
}
/////////////////////////////////////////////
void sortArray(){
 {
    int swapped;
    int i;
    for (i = 1; i <>
    {
swapped = 0;    //this flag is to check if the array is already sorted
int j;
for(j = 0; j <>
{
   if(array[j] > array[j+1])
   {
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
swapped = 1;
   }
}
if(!swapped){
   break; //if it is sorted then stop
}
    }
 }
}
////////////////////////////////////////////
int binarySearch(){

int left, right, midpt;
int loop=0;
left = 0;
right = size - 1;

while (left <= right)
{
midpt = (int) ((left + right) / 2);
printf("\nSearch#%d \tLow=%d \tHigh=%d \tMid=%d \tValue=%d\n",++loop,left,right,midpt,array[midpt]);
if (key == array[midpt])
{
return midpt;
}

else if (key > array[midpt])
left = midpt + 1;
else
right = midpt - 1;
}

return -1;
}

Comments

Popular posts from this blog

Unlock Your Future in Cybersecurity with Expert Online Training!