我无法在代码中实现二进制搜索,您能解释一下它是如何工作的。
binarySearch
接受一个整数数组a
和一个整数n
并使用
二进制搜索算法检查n
中是否包含a
。如果n
为
a
中包含的内容,以及打印已作出的决定和错误的数目
否则。
import java.util.Arrays;
import java.util.Random;
public class Excersice2 {
public static void main(String[] args) {
int[] arr = createArray(10);
System.out.println("the array not sorted");
printArray(arr);
arr = sortArray(arr);
System.out.println("the array sorted");
printArray(arr);
System.out.println(binarySearch(arr,50));
}
public static void printArray(int []arr)
{
System.out.println(Arrays.toString(arr));
}
public static int [] createArray(int n) {
int[] arr = new int[n];
Random rand = new Random();
for(int i = 0; i < n; i++)
arr[i] = rand.nextInt(101);
return arr;
}
public static int[] sortArray(int[] arr) {
Arrays.sort(arr);
return arr;
}
public static boolean binarySearch(int arr[], int n) {
int firstIdx = 0;
int lastIdx = - 1;
int middle = (firstIdx + lastIdx)/2;
int idx = arr.length/2;
while( firstIdx <= lastIdx) {
if(binarySearch[middle] < arr);
}
}
}
结果应如下所示: 花了2次才发现值50包含在数组中。浏览列表
答案 0 :(得分:2)
当您有一个数字数组并且对该数组进行了排序时,可以使用二进制搜索算法。 算法检查键(您要查找的数字)是否与数组的中间值相等。 如果是,则搜索完成并且键位于中间位置。 如果不是,则算法检查键是大于还是小于中间值。 如果更大,则该算法仅在数组的后半部分重复搜索,以中间的下一个位置为左。 如果小于,则仅在上半部分将中间位置之前的位置作为正确位置。 并重复该操作,直到找到键或数组中没有更多位置为止。
调用二进制搜索方法
//the number you are looking for. For example 4.
int key = 4;
//the first element of array
int left = 0;
//the last element of array
int right = arr.length - 1;
int pos = binarySearch(left, right, key);
if(pos == -1) { System.out.println("Array does not contain key"); }
else { System.out.println("Array contains key at position : " + pos); }
二进制搜索算法方法
int binarySearch(int left, int right, int key) {
int pos;
int mid;
if(left > right) {
//there is no more positions to search
pos = -1;
} else {
//Getting the middle position of array
mid = (left + right) / 2;
//if the key is the middle positions value
if(arr[mid] == key)
pos = mid;
//if the key is less than the middle value
else if(key < arr[mid])
//repeat the search only at the first half of array
pos = binarySearch(left, mid-1, key);
else
//else if the key is greater than the middle value
//search at the second half of array
pos = binarySearch(mid+1, right, key);
}
return pos;
}