-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ba2c8d4
commit d365dfa
Showing
1 changed file
with
23 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |