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 69 70 71 72 73 74 75 76 77 78
| @Test public void test_bsearch() { int a[] = new int[]{1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] search = new int[]{0, 1, 2, 7, 11}; for (int s : search) { System.out.println(String.format("begin Rsearch[%s]", s)); int idx = bsearch_recurse(a, 0, a.length - 1, s); System.out.println(String.format("end Rsearch[%s],index[%s]", s, idx)); }
for (int s : search) { System.out.println(String.format("begin Lsearch[%s]", s)); int idx = bsearch_while(a, s); System.out.println(String.format("end Lsearch[%s],index[%s]", s, idx)); } }
public int bsearch_recurse(int[] a, int from, int to, int tar) { System.out.println(String.format("search from[%s],to[%s]", from, to)); if (from > to || tar < a[from] || tar > a[to]) { return -1; } else if (tar == a[from]) { return from; } else if (tar == a[to]) { return to; } else { int m = (to + from) / 2; if (tar > a[m]) { return bsearch_recurse(a, m, to, tar); } else if (tar < a[m]) { return bsearch_recurse(a, from, m, tar); } else { return m; } } }
public int bsearch_while(int[] a, int tar) { int from = 0; int to = a.length - 1; if (to < 0 || tar < a[from] || tar > a[to]) { return -1; } else if (tar == a[from]) { return from; } else if (tar == a[to]) { return to; } else { int m = 0; while (from <= to) { m = (to + from) / 2; System.out.println(String.format("search from[%s],to[%s]", from, to)); if (tar < a[m]) { to = m - 1; } else if (tar > a[m]) { from = m + 1; } else { return m; } } } return -1; }
|