java实现二分查找,java实现二分,package cn.o
分享于 点击 25876 次 点评:30
java实现二分查找,java实现二分,package cn.o
package cn.outofmemory.snippets.core;import java.util.ArrayList;import java.util.Collections;public class BinarySearchArrayList { public static void main(String[] args) { /* Please note that the same API applies to any type of List implementation classes e.g. Vector etc */ // Create an ArrayList and populate it with elements ArrayList arrayList = new ArrayList(); arrayList.add("element_1"); arrayList.add("element_4"); arrayList.add("element_2"); arrayList.add("element_5"); arrayList.add("element_3"); /* static int binarySearch(List list, Object element) operation searches the provided List for the specified value using the binary search algorithm. Beware the source List must be sorted before it can be searched using this method. The method returns the index of the search value, if it is contained in the List; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the value would be inserted into the array */ Collections.sort(arrayList); // We search for a value that exists in the List (value element_2) int searchIndex1 = Collections.binarySearch(arrayList,"element_2"); System.out.println("Value element_2 found at index : " + searchIndex1); // We search for a value that does not exist in the array (value element_6) int searchIndex2 = Collections.binarySearch(arrayList,"element_6"); System.out.println("Value element_6 should be inserted at index : " + (-(searchIndex2) - 1)); }}
输出:
Value element_2 found at index : 1Value element_6 should be inserted at index : 5
用户点评