0
我正在研究一個程序,我必須演示一個線性和二分搜索算法的工作。爲此,我正在接受來自用戶的20個數字和搜索關鍵字的數組。代碼編譯,並且不會引發運行時錯誤。然而,當我搜索了一些,說12,在陣列中,而不是這個數字是在12位中印,上面說的數量在6位發現:線性和二進制搜索邏輯錯誤
import java.util.*;
class prg14
{
int num [] = new int [20];
int search;
public void lin (int arr[], int a)
{
num = arr;
search = a;
int i;
int flag = 0;
for (i=0; i<num.length; i++)
{
if (search == num[i])
{
flag = 1;
break;
}
}
if (flag == 1)
{
System.out.println("Linear Search : ");
System.out.println(a+ " found at position " + (i + 1));
}
else
{
System.out.println("Linear Search : ");
System.out.print(a+ " not present in the list \n");
}
}
public void binary(int array[], int a)
{
int first = 0;
int n = 20;
int last = n - 1;
int middle = (first + last)/2;
while(first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
System.out.println("Binary search : ");
System.out.println(search + " found at position " + (middle+1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
{System.out.println("Binary Search : ");
System.out.println(search + " not present in the list.\n");
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
prg14 obj = new prg14();
System.out.println("Enter any 20 numbers.");
String str;
int linn[] = new int[20];
int i;
for(i = 0; i<10; i++)
{
str = sc.next();
linn[i] = sc.nextInt();
}
System.out.println("Enter number to be searched.");
int search = sc.nextInt();
obj.lin(linn, search);
obj.binary(linn, search);
}
}
如何解決這個問題? TIA。
您確定值12不在位置6嗎?你爲什麼只讀10個值? –
二進制搜索對排序數組起作用。你確定輸入是按照排序的方式輸入的嗎? – BatScream
另一點,「如果(數組[中] ==搜索)...打印」發現在中間+1「 - 爲什麼+1? - 但是,如果語句數組[中]必須等於搜索,所以無論它打印的是正確的(減1) – Ben