首页 > 代码库 > 二分查找
二分查找
java
import java.util.Arrays;import java.util.Random;public class Solution { public void demo(int n) { if (n < 2) return; int[] array = new int[n]; Random rand = new Random(); for (int i = 0; i < array.length; i++) { array[i] = rand.nextInt(1000); } Arrays.sort(array); int value =http://www.mamicode.com/ array[rand.nextInt(n)]; for (int i = 0; i < array.length; i++) { value = array[i]; System.out.println("the number needs to be found:" + value); System.out.println("the position of value is:" + binSearch(0, array.length - 1, value, array)); System.out.println("the position of value is:" + binSearch1(value, array)); System.out.println("the position of value is:" + binSearch2(0, array.length - 1, value, array)); } System.out.println("**************"); for (int i = 0; i < array.length; i++) { System.out.println(i + ":" + array[i]); } System.out.println("**************"); } // 递归 public int binSearch(int low, int high, int value, int[] array) { int mid = (low + high) / 2; if (mid > 0 && mid < array.length - 1) { if (array[mid] == value) return mid; else if (array[mid] < value) { return binSearch(mid + 1, high, value, array); } else { return binSearch(low, mid - 1, value, array); } } if (array[low] == value) return low; if (array[high] == value) return high; return -1; } // 非递归 public int binSearch1(int value, int[] array) { int mid; int low = 0; int high = array.length - 1; while (low <= high) { mid = (low + high) / 2; if (array[mid] == value) { return mid; } else if (array[mid] > value) { high = mid - 1; } else { low = mid + 1; } } return -1; } // 改进递归 public int binSearch2(int low, int high, int value, int[] array) { if (low > high) return -1; int mid = low + (high - low) / 2; if (array[mid] == value) return mid; else if (array[mid] < value) { return binSearch2(mid + 1, high, value, array); } else { return binSearch2(low, mid - 1, value, array); } } public static void main(String[] args) { // TODO Auto-generated method stub Solution s = new Solution(); s.demo(13); }}
二分查找
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。