#include <stdio.h> | |
int main(void){ | |
// Binary search | |
// given a target and a sorted array | |
// find the midpoint of the current array | |
// if midpoint value is target return | |
// decide which half holds the target value | |
// repeat the steps with the subarray to the right or left of the current midpoint | |
int array[] = {2,4,6,8,10,12,14,16,18}; | |
int length = sizeof array/sizeof array[0]; | |
int start = 0; | |
int end = length-1; | |
int mid = (start + end) / 2; | |
int target = 2; | |
while(start <= end){ | |
if (array[mid] == target){ | |
printf("mid was target at position: %i\n", mid); | |
break; | |
} | |
if(target < array[mid]){ | |
end = mid-1; | |
mid = (start + end) / 2; | |
} | |
else{ | |
start = mid + 1; | |
mid = (start + end) / 2; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment