Skip to content

Commit

Permalink
Update binarySearch.c
Browse files Browse the repository at this point in the history
  • Loading branch information
RoyCoding8 authored Oct 2, 2023
1 parent ba2c8d4 commit d365dfa
Showing 1 changed file with 23 additions and 28 deletions.
51 changes: 23 additions & 28 deletions search/binary_search/C/binarySearch.c
Original file line number Diff line number Diff line change
@@ -1,37 +1,32 @@
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");
scanf("%d", &n);

printf("Enter %d integers\n", n);
int binarySearch(int arr[], int start, int end, int x) {

for (c = 0; c < n; c++)
scanf("%d", &array[c]);
if (start <= end) {

printf("Enter value to find\n");
scanf("%d", &search);
int mid = start + (end - start) / 2;

first = 0;
last = n - 1;
middle = (first+last)/2;
if (arr[mid] == x)
return mid;

while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
if (arr[mid] > x)
return binarySearch(arr, start, mid - 1, x);

middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return binarySearch(arr, mid + 1, end, x);
}
return -1;
}

return 0;
int main()
{
int arr[] = { 2, 3, 7, 8, 78, 99, 102, 5555 };
int x = 9;
int result = binarySearch(arr, 0, sizeof(arr) / sizeof(arr[0]), x);

if (result == -1) {
printf("Element not present");
}
else {
printf("Element found at index %d", result);
}
}

0 comments on commit d365dfa

Please sign in to comment.