-
Notifications
You must be signed in to change notification settings - Fork 302
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
binary_search.c: Add BinarySearch Algorithm
This adds Binary Search Algorithm which finds the position of a target value within a sorted array. It compares the target value to the middle element of the array. Closes http://github.com/NITSkmOS/Algorithms/issues/44
- Loading branch information
1 parent
967f5a1
commit a550689
Showing
2 changed files
with
56 additions
and
31 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
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 |
---|---|---|
@@ -0,0 +1,24 @@ | ||
#include <stdio.h> | ||
|
||
int binary_search(int arr[], int start, int end, int target) { | ||
while (start <= end) { | ||
int mid = start + (end - start) / 2; | ||
if (arr[mid] == target) { | ||
return mid; | ||
} else if (arr[mid] > target) { | ||
end = mid - 1; | ||
} else { | ||
start = mid + 1; | ||
} | ||
} | ||
return -1; | ||
} | ||
|
||
int main(void) { | ||
int arr[] = {-1, 0, 3, 4, 5, 6, 7, 8, 9}; | ||
int n = sizeof(arr) / sizeof(arr[0]); | ||
int target = -1; | ||
int result = binary_search(arr, 0, n - 1, target); | ||
printf("Index of %d in array is: %d \n", target, result); | ||
return 0; | ||
} |