Skip to content

Instantly share code, notes, and snippets.

@meagtan
Last active April 4, 2017 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meagtan/b37aaa1b9360bc0efd7f2e26169f1ef1 to your computer and use it in GitHub Desktop.
Save meagtan/b37aaa1b9360bc0efd7f2e26169f1ef1 to your computer and use it in GitHub Desktop.
Newton's method for sorted array search
/*
* 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