所以我遇到了递归程序的问题。该程序的作用是将文本文件作为具有未排序数字列表的输入。然后,它要求用户使用递归二进制搜索在数组中查找数字。如果找到该数字,则返回该数字的索引,如果不返回-1。现在这个程序返回-1表示任何输入,即使它在数组中。我不理解的部分是返回mid语句被调用,然后返回-1被调用几次。所以我很困惑我的程序如何运行到return语句但忽略它然后返回-1。这是我使用的文本文件中的数字。
31 70 5 71 140 187 162 98 153 8 109 103 145 157 27 23 136 54 19 168 114 25 139 129 94
这是程序本身。
import java.io.*;
import java.util.*;
public class Lab2
{
public static void main (String[] args) throws Exception
{
if (args.length < 1)
{
System.out.println( "Fatal Error. Enter a filename on the command line!\n");
System.exit(0);
}
int[] arr = new int[30]; // don't do the resizing thing. Leave that to Project#1
int cnt=0;
Scanner file1 = new Scanner( new FileReader(args[0]) );
while ( file1.hasNextInt() )
arr[cnt++]= file1.nextInt();
file1.close();
// print the array as it came from the file
printArray( "original array: ", arr, cnt );
// sort using Arrays.sort (see utils API)
Arrays.sort( arr, 0, cnt ); // 2nd index non inclusive - i.e. cnt-1
// re-print it - should come out sorted
printArray( "sorted array: ", arr, cnt );
// now search the sorted array using YOUR bSearch
Scanner kbd = new Scanner( System.in );
do
{
System.out.print("Enter number to search for: ");
int key = kbd.nextInt();
if ( key <= 0) break; // ENTER ZERO OR NEGATIVE TO QUIT LOOP
int index=bSearch( arr, 0, cnt-1, key );
if ( index < 0 )
System.out.println( key + " not found at index: " + index);
else
System.out.println( key + " found at index: " + index);
}
while ( true ); // infinite loop. Must break to get out
} // END main
// ======================================================================
// M E T H O D S
// ======================================================================
// return the index where key was found
// else return -1 for not found
static int bSearch(int[] array, int low, int high, int key)
{
int mid;
if (low <= high)
{
mid = (low+high)/2;
if (array[mid] < key)
{
bSearch(array, mid+1, high, key);
}
else if (array[mid] > key)
{
bSearch(array, low, mid-1, key);
}
else {
System.out.println("this is true");
return mid;
}
}
System.out.println("why is this returning");
return -1;
}
// USE THIS METHOD AS GIVEN: DO NOT CHANGE
private static void printArray( String label, int[] array, int count )
{
System.out.print(label);
for( int i=0 ; i<count ;++i )
System.out.print(array[i] + " " );
System.out.println("\n");
}
答案 0 :(得分:1)
你错过了2回复声明。
if (array[mid] < key)
{
return bSearch(array, mid+1, high, key);
}
else if (array[mid] > key)
{
return bSearch(array, low, mid-1, key);
}
答案 1 :(得分:1)
你正在打电话给bsearch,但你没有回复答案。说bsearch(...
的两行都应该说return bsearch(...
。