查找—折半查找
该查找只针对于已经排好序的进行查找操作,很有局限性。
package com.ufida.practice.suanfa.search; import java.util.ArrayList; import java.util.List; import java.util.Random; public class BinarySearch { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) list.add(i); for(int i : list) System.out.print(i+" "); System.out.println("~~~~~~~~~~~~~~~~~~~"); int num = new Random().nextInt(15); System.out.println("找到了"+num+",位置为:"+BinarySearch(list,num)); } public static int BinarySearch(List<Integer> list, int key) { //最低线 int low = 0; //最高线 int high = list.size() - 1; while (low <= high) { //取中间值 int middle = (low + high) / 2; if (list.get(middle) == key) { return middle; } else if (list.get(middle) > key) { //下降一半 high = middle - 1; } else { //上升一半 low = middle + 1; } } //未找到 return -1; } }
因为年轻,所有没有失败。