Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 41 additions & 27 deletions C/algorithms/searching/binary_search.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,46 @@
*/

#include <stdio.h>
#define SIZE 10
int BinarySearch(int [],int);
int main()
{
int a[SIZE]={3,5,9,11,15,17,22,25,37,68},key,pos;
printf("Enter the Search Key\n");
scanf("%d",&key);
pos=BinarySearch(a,key);
if(pos==-1)
printf("The search key is not in the array\n");
else
printf("The search key %d is at location %d\n",key,pos);
return 0;
//function to perform binary search
int binarySearch(int arr[], int size, int key) {
int low = 0, high = size - 1, mid;

while (low <= high) {
mid = (low + high) / 2;

if (arr[mid] == key)
return mid;
else if (key < arr[mid])
high = mid - 1;
else
low = mid + 1;
}

int BinarySearch (int A[],int skey)
{
int low=0,high=SIZE-1,middle;
while (low <=high){
middle=(low+high)/2;
if(skey==A[middle])
return middle;
else if(skey <A[middle])
high=middle-1;
else
low=middle+1;
}
return -1;
}
return -1;
}
int main() {
int size, key, position;

printf("Enter the number of elements: ");
scanf("%d", &size);

int arr[size];

printf("Enter %d elements in ascending order:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the number to search: ");
scanf("%d", &key);

position = binarySearch(arr, size, key);

if (position == -1)
printf("The number %d was not found in the array.\n", key);
else
printf("The number %d was found at index %d (position %d).\n", key, position, position + 1);

return 0;
}