package com.my.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainTest { public static void main(String[] args) { List<Integer> list = new ArrayList(); list.add(new Integer(13)); list.add(new Integer(14)); list.add(new Integer(13)); list.add(new Integer(34)); list.add(new Integer(23)); list.add(new Integer(54)); list.add(new Integer(63)); list.add(new Integer(04)); Collections.sort(list); Integer[] arr = list.toArray(new Integer[list.size()]); System.out.println(System.currentTimeMillis()); int a = BinarySearch(arr, 0, arr.length, 3); System.out.println(System.currentTimeMillis()); System.out.println(a); } public static Integer BinarySearch(Integer[] arr, int start, int end, int dest) { if (start < end) { // 中间位置 int middle = (start + end) >> 1;// 相当于s+e/2 // 中间值 int mid = arr[middle]; if (dest == mid) { return mid; } else if (dest < mid) { // 在左侧找 return BinarySearch(arr, start, middle - 1, dest); } else if (dest > mid) {// 右侧找 return BinarySearch(arr, middle + 1, end, dest); }else{ return -1; } } return -1; } }
时间: 2024-10-07 07:41:44