Changeset 13577 for issm/trunk-jpl/src/c/shared
- Timestamp:
- 10/10/12 07:39:19 (13 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
issm/trunk-jpl/src/c/shared/Sorting/binary_search.cpp
r13575 r13577 64 64 return found; 65 65 } /*}}}*/ 66 int binary_search(int* poffset,double target,double* list,int num_doubles){ /*{{{*/ 66 int binary_search(int* poffset,double target,double* list,int length){ /*{{{*/ 67 /* 68 * l[0] l[1] l[2] l[n] l[n+1] l[length-1] 69 * <-------+-----+-----+-----+ ... +-----+........+--------------> 70 * offset: -1 0 1 2 n length -1 71 * 72 * offset = -1 target < list[0] 73 * offset = n list[n] <= target < list[n+1] 74 * offset = length-1 list[length-1] <= target 75 */ 67 76 68 77 /*output: */ 69 78 int offset = 0; 70 int found = 0; /*found = 0: not found. 71 found = -1: found, and target is < first element 72 found = 1: found, and target is == to value at offset 73 found = 2: found, and target is > to value at offset and < to value at offset+1 74 found = 3: found, and target is >= last value */ 79 int found = 0; 75 80 76 81 /*intermediary: */ 77 82 int n0 = 0; 78 int n1 = int( num_doubles/2);79 int n2 = num_doubles-1;83 int n1 = int(length/2); 84 int n2 = length-1; 80 85 81 86 if(target<list[n0]){ 82 found = -1;87 found = 1; 83 88 offset = -1; 84 89 } 85 90 else if(target>=list[n2]){ 86 found = 3;87 offset = n2-1;91 found = 1; 92 offset = length-1; 88 93 } 89 94 else{ 90 while(!found){95 for(;;){ 91 96 /*did we find the target?*/ 92 97 if(list[n1]<=target && list[n1+1]>target){ 93 found = 1;98 found = 1; 94 99 offset = n1; 95 100 break; 96 101 } 97 if(target < list[n1]){102 else if(target < list[n1]){ 98 103 n2 = n1; 99 104 n1 = n0 + int((n2-n0)/2); … … 104 109 } 105 110 } 106 107 //did we find an exact target?108 if(list[n1]==target) found = 2;109 111 } 110 112 111 /*Assign output pointer s:*/113 /*Assign output pointer and return*/ 112 114 *poffset=offset; 113 114 /*Return result: */115 115 return found; 116 116 } /*}}}*/
Note:
See TracChangeset
for help on using the changeset viewer.