【发布时间】:2023-03-14 21:24:01
【问题描述】:
编写一个程序,从文本文件中读取整数,然后对数字进行排序。然后使用笔记中的二分搜索算法(第 6 周)要求用户输入一个数字,如果该数字不在列表中,则显示该数字在哪个位置或未找到。
到目前为止我的代码:
import java.util.Arrays;
public class myBinarySearch
{
public static void main(String[] args)
{
int i;
int target, found;
int[] numArray = {36, 27, 29, 15, 16, 39, 11, 31};
Arrays.sort(numArray);
for(i=0; i <numArray.length; i++)
System.out.print(numArray[i] + " ");
System.out.print("\nEnter the number you are searching for: ");
target = ReadKb.getInt();
found = theBinarySearch(numArray, target);
if(found == -1)
System.out.println("Number not found");
else
System.out.println("Number: " +target +" found at position: " +found);
}
//Method searching using binary search algorithm
private static int theBinarySearch(int []numArray, int target)
{
int mid,bottom,top;
mid=0;
bottom=0;
top=numArray.length-1;
while (top>= bottom)
{
mid=(top +bottom)/2;
if(target==numArray[mid])
break;
else
if(target<numArray[mid])
top=mid-1;
else
bottom=mid+1;
}
if(target==numArray[mid])
return mid;
else
return -1;
}
}
还有txt文档:
数字.txt 55 12 88 33 25 5 3 23 64 21
【问题讨论】: