标签:style blog color java os ar art div
import java.util.Arrays; /* * 二分查找 */ public class BinarySearch { /* * while循环 */ public static int binarySearch(int[] ls, int su) { int low = 0; int high = ls.length - 1; while (low <= high) { int avg = (low + high) / 2; if (su == ls[avg]) { return avg; } else if (su > ls[avg]) { low = avg + 1; } else if (su < ls[avg]) { high = avg - 1; } } return -1; } /* * 递归 */ public static int binarySearch(int[] ls, int startindex, int endindex, int su) { int avg = (startindex + endindex) / 2; if (startindex > endindex || su < ls[startindex] || su > ls[endindex]) { return -1; } if (su == ls[avg]) { return avg; } else if (su > ls[avg]) { return binarySearch(ls, avg + 1, endindex, su); } else if (su < ls[avg]) { return binarySearch(ls, startindex, avg - 1, su); } return -1; } public static void main(String[] args) { // TODO Auto-generated method stub int[] ls = { 3, 6, 4, 9, 8, 12, 13, 21, 5, 16, 7, 0, 1, 2 }; // 排序 Arrays.sort(ls); System.out.println(Arrays.toString(ls)); int su = 16; // while 循环 System.out.println(binarySearch(ls, su)); // 递归 System.out.println(binarySearch(ls, 0, ls.length - 1, su)); // Arrays 方法 System.out.println(Arrays.binarySearch(ls, su)); } }
输出 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 16, 21] 11 11 11
标签:style blog color java os ar art div
原文地址:http://www.cnblogs.com/loveismile/p/3906043.html