|
Binary search is for a small to an array of large sorted to find a number val, first comparison to be looking for the number of val and intermediate value, if greater than the median, then in the middle right of the value to find; if the ratio of the median small , then the median left to find. It has been recursion. You know where to find val. If not found, then the output sequence there is no relevant data.
package com.PengRong.A;
public class BinaryFind {
public static void main (String [] args) {
// TODO Auto-generated method stub
int [] arr = {1, 5, 9, 56, 78, 80, 85, 99}; // Note that the array needs from small to large sorted.
// If more data needs to be sorted by the sorting algorithm can use binary search Hair
BinFind binfin = new BinFind ();
binfin.binaryFind (0, arr.length-1, 85, arr);
}
}
class BinFind
{
/ **
* @param Left left array subscript
* @param Right and an array subscript
* @param Arr an array reference
* @param Val to be looking for a few
* @ Functions: a bunch of numbers to find whether there val number, call the binary search method provided that this is an orderly sequence arr
* /
public void binaryFind (int left, int right, int val, int [] arr)
{
// Binary search is actually through the array must be such that no more than the right of the left subscript subscript
if (left < = right)
{
// Find the middle number
int pivot = arr [(left + right) / 2];
// If you're looking for the number is smaller than the median in the middle of the left to find value
if (val < pivot)
{
binaryFind (left, (left + right) / 2-1, val, arr);
} Else if (val> pivot)
// If you are looking for a number greater than the median in the middle right of the value to find
{
binaryFind ((left + right) / 2 +1, right, val, arr);
} Else if (val == pivot)
{
System.out.println ( "found in the array sequence" + val + "this number, its index is:" + ((left + right) / 2));
}
}
else
{
System.out.println ( "I'm sorry the number you are looking for is not in the array sequence");
}
}
} |
|
|
|