Binary lookup, also known as binary search (binary search), requires an array of ordered (sort), by comparing the intermediate data of the array (center-biased method) to determine the scope of the lookup value;
Until the median value equals the lookup value, the lookup succeeds; If unsuccessful, reset the data, judge the size of the beginning and end position, then carry on the median comparison; If the judgment fails, the data does not exist;
Attention:
1. Eclipse cannot redirect (redirect) input files (file) and read only data;
2. Use cmd redirect input file, you need to extract "Stdlib.jar", take out the corresponding class (in, out, StdIn, StdOut), put into the execution directory, otherwise it will be an error:
Error: Java.lang.NoClassDefFoundError, that is, the corresponding class file could not be found, will be able to perform eclipse, CMD can not execute the situation;
Code main function: To determine whether to find success, failure to output lookup data;
Command line: Java-classpath D:\eclipse\dropins\stdlib.jar; BinarySearch TinyW.txt < TinyT.txt
The code is as follows:
* * * * Algorithms.java * * Created on:2013.12.02 * Author:wendy//*eclipse std Kepler, stdlib.
jar*/import java.util.Arrays;
public class Algorithms {/* binary lookup algorithm (binary search) */public static int rank (int key, int[] a) {
int lo = 0;
int hi = a.length-1; while (lo <= hi) {int mid = lo + (Hi-lo)/2;//Integer down whole if (key < A[mid]) hi
= Mid-1;
else if (key > A[mid]) lo = mid + 1;
else return mid;
} return-1;
public static void Main (string[] args) {in ' = new in (Args[0]); Int[] Whitelist = in.readallints (); Reads the original array arrays.sort (whitelist); Sort while (!
Stdin.isempty ())//To determine whether the redirected data is empty {int key = Stdin.readint ();
if (rank (key, whitelist) = = 1)//output does not exist the data stdout.println (key); }
}
}
Output:
Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/