gpt4 book ai didi

java - 实现二分查找

转载 作者:行者123 更新时间:2023-12-01 19:22:38 25 4
gpt4 key购买 nike

import java.io.*;
import java.lang.Integer;

class sort {
public void find(int val, int a[], int n) {
int mid = n / 2;
System.out.println("the mid value is:" + a[mid]);
if (a[mid] == val) {
System.out.println("found " + a[mid] + " in position " + mid);
} else if (a[mid] < val) {
for (int i = mid; i < n; i++) {
if (a[mid] == val) {
System.out.println("found" + val);
}
}
} else if (a[mid] > val) {
for (int i =0; i < mid; i++) {
if (a[mid] == val) {
System.out.println("found" + val);
}
}
}
}


public static void main(String args[])throws IOException {
DataInputStream in = new DataInputStream(System.in);
int temp;
int a[] = new int[100];
System.out.println("enter the nos of elements");
int n = Integer.parseInt(in.readLine());
for (int i =0; i < n; i++) {
a[i] = Integer.parseInt(in.readLine());
}
for (int i =0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i =0; i < n; i++) {
System.out.println(a[i]);
}

System.out.println("enter the value to be searched");
int val = Integer.parseInt(in.readLine());
sort s = new sort();
s.find(val, a, n);
}
}

通过上面的代码,我想使用二分搜索从现有数组列表中查找用户定义的值。它仅检查中间值,而不检查较高或较低的值。

我认为循环无法正常工作。

请找到解决方案。

最佳答案

你的两个内部循环:

for(int i=mid;i<n;i++) 
{
if (a[mid] ==val)
System.out.println("found"+val);
}



for(int i=0;i<mid;i++)
{
if ( a[mid] ==val)
System.out.println("found"+val);
}

请注意,您正在访问 a[mid]mid 在整个循环中不会改变;您打算使用a[i]。尝试用 i 替换 mid

此外,您可能需要考虑缩进代码。您使用什么编辑器来编写代码?

关于java - 实现二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3274454/

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