【发布时间】:2014-03-31 20:33:09
【问题描述】:
所以我遇到了递归程序的问题。该程序的作用是将文本文件作为输入,其中包含未排序的数字列表。然后它要求用户使用递归二进制搜索在数组中找到一个数字。如果找到数字,则返回该数字的索引,否则返回 -1。现在这个程序在这里为任何输入返回-1,即使它在数组中。我不明白的部分是 return mid 语句被调用,然后 return -1 被调用了几次。所以我对我的程序如何运行返回语句但忽略它然后返回-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");
}
【问题讨论】:
标签: java recursion return return-value