Skip to content

Instantly share code, notes, and snippets.

@richzw
Last active December 11, 2015 22:28
Show Gist options
  • Save richzw/4669716 to your computer and use it in GitHub Desktop.
Save richzw/4669716 to your computer and use it in GitHub Desktop.
一个有序数组(从小到大排列),数组中的数据有正有负,求这个数组中的最小绝对值
9 /*
10 * binary search
11 */
12 int findMin_binary(int arr[], int left, int right){
13 if (NULL == arr)
14 return 0;
15
16 while(left < right){
17 if (arr[left] > 0)
18 return arr[left];
19 if (arr[right] < 0)
20 return arr[right];
21
22 if (right - left == 1){
23 return abs(arr[left]) > abs(arr[right])? (arr[right]) : (arr[left]);
24 }
25
26 int mid = (left & right) + ((left ^ right) >> 1);
27 if (arr[mid] > 0){
28 right = mid;
29 }else{
30 left = mid;
31 }
32 }
33 }
35 /*
36 * Ternary search http://en.wikipedia.org/wiki/Ternary_search
37 */
38 int findMin_ternary(int arr[], int left, int right){
39 if (NULL == arr)
40 return 0;
41
42 while(left < right){
43 if (arr[left] > 0)
44 return arr[left];
45 if (arr[right] < 0)
46 return arr[right];
47
48 if (right - left == 2){
49 int mid = (left + right) >> 1;
50 int less_min = abs(arr[left]) > abs(arr[right])? (arr[right]) : (arr[left]);
51 return abs(arr[mid]) > abs(less_min) ? less_min : arr[mid];
52 }
53
54 int left_third = (2*left + right)/3;
55 int right_third = (left + 2*right)/3;
56 if(abs(arr[left_third]) > abs(arr[right_third]))
57 left = left_third;
58 else
59 right = right_third;
60 }
61 }
double phi = (1 + Math.sqrt(5)) / 2;
double resphi = 2 - phi;
// a and c are the current bounds; the minimum is between them.
// b is a center point
// f(x) is some mathematical function elsewhere defined
// a corresponds to x1; b corresponds to x2; c corresponds to x3
// x corresponds to x4
public double goldenSectionSearch(double a, double b, double c, double tau) {
double x;
if (c - b > b - a)
x = b + resphi * (c - b);
else
x = b - resphi * (b - a);
if (Math.abs(c - a) < tau * (Math.abs(b) + Math.abs(x)))
return (c + a) / 2;
assert(f(x) != f(b));
if (f(x) < f(b)) {
if (c - b > b - a) return goldenSectionSearch(b, x, c, tau);
else return goldenSectionSearch(a, x, b, tau);
}
else {
if (c - b > b - a) return goldenSectionSearch(a, b, x, tau);
else return goldenSectionSearch(x, b, c, tau);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment