/*PROGRAM TO IMPLEMENT BINARY SEARCH IN 1-DIMENSIONAL ARRAY.
THE UNSORTED ARRAY IS SORTED IS SORTED WHICH IS THE REQUIREMENT OF BINARY SEARCH.
************************************************************/
#include<stdio.h>
#include<conio.h>
#define size 20
int searchBinary(int arr[], int number, int item)
{
//SORTING
int min, low, i, j, temp;
for(i= 0; i < number; ++i)
{
min = arr[i]; low =i;
for(j = i+1; j < number; ++j)
{
if(min >= arr[j])
{
low = j;
min = arr[j];
}
}
temp = arr[i];
arr[i] = arr[low];
arr[low] = temp;
}
printf("\n\nSORTED Numbers...\n");
for(i= 0; i < number; ++i)
{
printf("%d ",arr[i]);
}
//SORTING DONE
int first=0, end = number-1, mid = int((first+end)/2);
while(first <= end)
{
mid = int((first+end)/2);
if(arr[mid] == item)
return(2);
else if(arr[mid] > item)
end = mid-1;
else
first = mid+1;
}
return -1;
}
int main()
{
int array[size], num, data;
printf("\nHow many elements...?");
scanf("%d",&num);
if(num>20)
num = 20;
for(int i = 0 ; i < num ; ++ i)
{
printf("\nElement number %2d : ", i+1);
scanf("%d",&array[i]);
}
printf("\n\nEnter element to be searched... :");
scanf("%d", &data);
int index;
index = searchBinary(array, num, data);
if(index == 2)
printf("\n\nElement found");
else
printf("\n\nElement not found");
getch();
return 0;
}
THE UNSORTED ARRAY IS SORTED IS SORTED WHICH IS THE REQUIREMENT OF BINARY SEARCH.
************************************************************/
#include<stdio.h>
#include<conio.h>
#define size 20
int searchBinary(int arr[], int number, int item)
{
//SORTING
int min, low, i, j, temp;
for(i= 0; i < number; ++i)
{
min = arr[i]; low =i;
for(j = i+1; j < number; ++j)
{
if(min >= arr[j])
{
low = j;
min = arr[j];
}
}
temp = arr[i];
arr[i] = arr[low];
arr[low] = temp;
}
printf("\n\nSORTED Numbers...\n");
for(i= 0; i < number; ++i)
{
printf("%d ",arr[i]);
}
//SORTING DONE
int first=0, end = number-1, mid = int((first+end)/2);
while(first <= end)
{
mid = int((first+end)/2);
if(arr[mid] == item)
return(2);
else if(arr[mid] > item)
end = mid-1;
else
first = mid+1;
}
return -1;
}
int main()
{
int array[size], num, data;
printf("\nHow many elements...?");
scanf("%d",&num);
if(num>20)
num = 20;
for(int i = 0 ; i < num ; ++ i)
{
printf("\nElement number %2d : ", i+1);
scanf("%d",&array[i]);
}
printf("\n\nEnter element to be searched... :");
scanf("%d", &data);
int index;
index = searchBinary(array, num, data);
if(index == 2)
printf("\n\nElement found");
else
printf("\n\nElement not found");
getch();
return 0;
}