File: bsearch.c

package info (click to toggle)
funtools 1.4.4+dfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 16,168 kB
  • ctags: 10,760
  • sloc: ansic: 87,238; sh: 9,727; lex: 4,595; asm: 3,281; ada: 1,681; makefile: 1,458; pascal: 1,089; cpp: 1,001; cs: 879; perl: 161; yacc: 64; sed: 32; csh: 10; tcl: 9
file content (68 lines) | stat: -rw-r--r-- 1,410 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary */

/* returns first target if more than one have same value */
static public int search(int [] array, int target)
{
  int high = array.length, low = -1, probe;
  while (high - low > 1)
    {
      probe = (high + low) / 2;
      if (array[probe] < target)
	low = probe;
      else
	high = probe;
    }
  if (high == array.length || array[high] != target)
    return -1;
  else
    return high;
}

/* returns last target if more than one have same value */
static public int search2(int [] array, int target)
{
  int high = array.length, low = -1, probe;
  while (high - low > 1)
    {
      probe = (high + low) / 2;
      if (array[probe] > target)
	high = probe;
      else
	low = probe;
    }
  if (low == -1 || array[low] != target)
    return -1;
  else
    return low;
}

static public int [] range(int [] array, int floor, int ceiling)
{
  int [] answer = new int[2];
  int high, low, probe;

  // work on floor
  high = array.length; low = -1;
  while (high - low > 1)
    {
      probe = (high + low) / 2;
      if (array[probe] < floor)
	low = probe;
      else
	high = probe;
    }
  answer[0] = low;

  // work on ceiling
  high = array.length; low = -1;
  while (high - low > 1)
    {
      probe = (high + low) / 2;
      if (array[probe] > ceiling)
	high = probe;
      else
	low = probe;
    }
  answer[1] = high;
  return answer;
}