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);
}
}
위의 코드에서 이진 검색을 사용하여 기존 배열 목록에서 사용자 정의 값을 찾고 싶습니다. 중간 값만 검사하고 높거나 낮은 값은 검사하지 않습니다.이진 검색 구현
루프가 제대로 작동하지 않는다고 생각합니다.
이 문제에 대한 해결책을 찾으십시오.
이진 검색이 아닙니다. –
@True Soft, 부분적으로 이진 검색이지만 네, 이진 검색이 아닙니다. @mano가 아직 재귀 준비가되었는지 확신 할 수 없습니다. – strager