Navigation

  • index
  • next |
  • previous |
  • k14i.github.io 1.0.0 documentation »
  • Computer Science »
  • Algorithm »

Binary Search¶

Examples¶

Java¶

int binarySearch(int[] a, int x) {
  int low = 0;
  int high = a.length - 1;
  int mid;

  while (low <= high) {
    mid = (low + high) / 2;
    if (a[mid] < x) {
      low = mid + 1;
    } else if (a[mid] > x) {
      high = mid = 1;
    } else {
      return mid;
    }
  }
  return -1;
}

int binarySearchRecursive(int[] a, int x, int low, int high) {
  if (low > high) return -1;

  int mid = (low + high) / 2;
  if (a[mid] < x) {
    return binarySearchRecursive(a, x, mid + 1, high);
  } else if (a[mid] > x) {
    return binarySearchRecursive(a, x, low, mid - 1);
  } else {
    return mid;
  }
}

My repository

Table Of Contents

  • Computer Science
  • Elixir
  • C
  • Programming Languages
  • Operation and Monitoring
  • GlusterFS
  • Docker
  • Bayes’ theorem
  • Personal Data Protection
  • Sphinx
  • Presentation
  • Erlang Factory SF Bay Area 2014
  • Strata + Hadoop World 2015
  • Timeline
  • Favorite Tweets

Previous topic

DP: Dynamic Programming

Next topic

値の交換

This Page

  • Show Source

Quick search

Navigation

  • index
  • next |
  • previous |
  • k14i.github.io 1.0.0 documentation »
  • Computer Science »
  • Algorithm »
© Copyright 2015-2021, Keisuke Takahashi. Created using Sphinx 1.7.9.