gpt4 book ai didi

Java二分查找计数比较次数

转载 作者:搜寻专家 更新时间:2023-11-01 01:20:24 25 4
gpt4 key购买 nike

我在 java 中编写了以下用于二分查找的代码:

import java.util.Arrays;

class BinarySearch {
public static int binarySearch(double[] arr, double x, int high, int low) {
int mid=(high+low)/2;
if(high==low || low==mid || high==mid) {
return -1;
}
if(arr[mid]<x) {
return binarySearch(arr, x, high, mid);
}
else if(arr[mid]>x) {
return binarySearch(arr, x, mid, low);
}
else if(arr[mid]==x) {
return mid;
}
return -1;
}

public static void main(String args[]) {
int n=1000;
double array[] = new double[n];
for (int i=0; i<100; i++) {
for (int k = 0; k < n; k++) {
double r = Math.random();
r = r * 100;
r = Math.round(r);
r = r / 100;
array[k] = r;
}
Arrays.sort(array);
double search = Math.random();
search = search * 100;
search = Math.round(search);
search = search / 100;
int result=binarySearch(array, search, n, 0);
if (result == -1)
System.out.println(search +" befindet sich nicht im Array.");
else
System.out.println(search+" befindet sich im Array an der Stelle "+(result)+".");
}
}

我想看看二分搜索需要进行多少次比较才能找到这个数字,但我不知道如何实现。我已经做了一个循环,所以我可以看到比较的平均值,但我不知道如何获得比较的次数。

最佳答案

您可以这样做以使事情变得简单。

private static int comparisions = 0;

public static int binarySearch(double[] arr, double x, int high, int low) {
int mid = (high + low) / 2;
if (high == low || low == mid || high == mid) {
comparisions++;
return -1;
}
if (arr[mid] < x) {
comparisions++;
return binarySearch(arr, x, high, mid);
} else if (arr[mid] > x) {
comparisions++;
return binarySearch(arr, x, mid, low);
} else if (arr[mid] == x) {
comparisions++;
return mid;
}
return -1;
}

public static void main(String args[]) {
int n = 1000;
double array[] = new double[n];
for (int i = 0; i < 100; i++) {
for (int k = 0; k < n; k++) {
double r = Math.random();
r = r * 100;
r = Math.round(r);
r = r / 100;
array[k] = r;
}
Arrays.sort(array);
double search = Math.random();
search = search * 100;
search = Math.round(search);
search = search / 100;
int result = binarySearch(array, search, n, 0);
System.out.println("Number of comparisions " + comparisions);
if (result == -1)
System.out.println(search + " befindet sich nicht im Array.");
else
System.out.println(search + " befindet sich im Array an der Stelle " + (result) + ".");
}

}

关于Java二分查找计数比较次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com