gpt4 book ai didi

java - 使用 Java 进行排序和二分搜索

转载 作者:行者123 更新时间:2023-12-01 17:19:52 39 4
gpt4 key购买 nike

我被要求对数组进行排序和搜索。对数组进行排序很简单,我的代码也有效,但每当我尝试调用二分搜索方法时,它都会对数组中的第一个元素起作用,但结果会给出“-1”

我的完整代码如下:

 public static void main(String[] args) {

int[] array = new int[5];
array[0] = 50;
array[1] = 40;
array[2] = 10;
array[3] = 20;
array[4] = 100;

sort(array, (array.length - 1));

for (int x = 0; x < array.length; x++) {
System.out.println(" " + array[x]);
}
System.out.println("");
System.out.println("Binary search (R): " + rBsearch(array, 0, (array.length), 20));
}
public static void sort(int[] a, int last) {
if (last > 0) {
int max = findMax(a, last);
swap(a, last, max);
sort(a, last - 1);
}
}

public static int rBsearch(int[] L, int low, int high, int k) {


int mid = (low + high) / 2;

if (low > high) {
return -1;
} else if (L[mid] == k) {
return mid;
} else if (L[mid] < k) {
return rBsearch(L, k, mid + 1, high);
} else {
return rBsearch(L, k, low, mid - 1);
}
}

public static int findMax(int[] arr, int last) {

int max = 0;
for (int i = 0; i <= last; i++) {
if (arr[i] > arr[max]) {
max = i;
}
}
return max;
}

public static void swap(int[] arr, int last, int max) {
int temp = arr[last];
arr[last] = arr[max];
arr[max] = temp;
}

最佳答案

你弄乱了二分搜索间隔

public static int rBsearch(int[] L, int low, int high, int k) {


int mid = (low + high) / 2;

if (low > high) {
return -1;
} else if (L[mid] == k) {
return L[mid];
} else if (L[mid] < k) {
return rBsearch(L, mid + 1, high, k);
} else {
return rBsearch(L, low, mid - 1, k);
}
}

关于java - 使用 Java 进行排序和二分搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19492402/

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