[英]Linear and Binary search logical error
我正在開發一個程序,在這里我必須演示線性和二進制搜索算法的工作原理。 為此,我要從用戶那里獲取一個由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。
刪除String str
,就像
for( i = 0; i<linn.length; i++)
{
// str = sc.next();
linn[i] = sc.nextInt();
}
您無需混合行輸入和標記化輸入,因此無需擔心尾隨換行符(在這種情況下)。 另外,我將通過返回匹配的索引(或-1,如果未找到)來實現線性搜索功能
public static int linear(int arr[], int a) {
for (int pos = 0; pos < arr.length; pos++) {
if (arr[pos] == a) {
return pos;
}
}
return -1;
}
我將對binarySearch做同樣的事情。 這樣,您可以將消息顯示與計算分開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.