Ice Sheet System Model  4.18
Code documentation
sorting.h
Go to the documentation of this file.
1 
5 #ifndef _SORTING_H_
6 #define _SORTING_H_
7 
8 int binary_search(int* poffset,int target,int* sorted_integers,int num_integers);
9 template <typename doubletype> int binary_search(int* poffset,doubletype target,doubletype* list,int length){ /*{{{*/
10  /*
11  * l[0] l[1] l[2] l[n] l[n+1] l[length-1]
12  * <-------+-----+-----+-----+ ... +-----+........+-------------->
13  * offset: -1 0 1 2 n length -1
14  *
15  * offset = -1 target < list[0]
16  * offset = n list[n] <= target < list[n+1]
17  * offset = length-1 list[length-1] <= target
18  */
19 
20  /*output: */
21  int offset = 0;
22  int found = 0;
23 
24  /*intermediary: */
25  int n0 = 0;
26  int n1 = int(length/2);
27  int n2 = length-1;
28 
29  if(target<list[n0]){
30  found = 1;
31  offset = -1;
32  }
33  else if(target>=list[n2]){
34  found = 1;
35  offset = length-1;
36  }
37  else{
38  for(;;){
39  /*did we find the target?*/
40  if(list[n1]<=target && list[n1+1]>target){
41  found = 1;
42  offset = n1;
43  break;
44  }
45  else if(target < list[n1]){
46  n2 = n1;
47  n1 = n0 + int((n2-n0)/2);
48  }
49  else{
50  n0 = n1;
51  n1 = n0 + int((n2-n0)/2);
52  }
53  }
54  }
55 
56  /*Assign output pointer and return*/
57  *poffset=offset;
58  return found;
59 } /*}}}*/
60 
61 #endif //ifndef _SORTING_H_
binary_search
int binary_search(int *poffset, int target, int *sorted_integers, int num_integers)
Definition: binary_search.cpp:14