Last active
April 4, 2017 13:37
-
-
Save meagtan/b37aaa1b9360bc0efd7f2e26169f1ef1 to your computer and use it in GitHub Desktop.
Newton's method for sorted array search
This file contains hidden or 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
/* | |
* Search for integer a in sorted array arr[n] similarly to Newton's method | |
*/ | |
int newtonsearch(int *arr, int n, int a) | |
{ | |
int i = 0; | |
while (i >= 0 && i < n) { | |
if (arr[i] == a) | |
return i; | |
i -= (arr[i] - a) / (arr[i + 1] - arr[i]); // TODO check for boundary conditions, zero denominator, rounding errors | |
// i may oscillate between two points or stop, check those conditions | |
} | |
return -1; | |
} | |
/* | |
* Regular binary search on sorted array, analogous to interval cutting for numerical optimization | |
*/ | |
int binsearch(int *arr, int n, int a) | |
{ | |
int max = n - 1, min = 0, mid; | |
for (mid = max / 2; min < max && arr[mid] != a; mid = (max + min) / 2) { | |
if (arr[mid] > a) | |
min = mid; | |
else | |
max = mid; | |
} | |
return arr[mid] == a ? mid : -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment