繁体   English   中英

二进制搜索数字和报价?

[英]Binary Search on a number as well as a quote?

对于我的一个类,我必须使用二进制搜索首先查看报价是否存在(通过查找报价编号),然后将报价打印出来。 在文本文件中,每个引号都有两行。

第一行包含引号,第二行为引号。 报价号已经为该程序排序。

该程序的要求如下:创建一个将引号读入数组的程序。 (完成)然后,用户将根据输入的数字请求标题。 (完成)然后,程序将使用二进制搜索来查找报价(如果存在)。 我目前拥有大部分,但似乎无法使用。 我从数组列表读取到数组,但是在此之后我一无所知。 我已经在这个问题上停留了一段时间,任何帮助将不胜感激!

编辑:**现有代码只是将其读入数组。 我正在尝试做的是查看该数字是否存在,如果确实存在,则从文本文件中打印出其下方的引号。 如果不存在,则打印不存在。 **

该程序应该大致如下所示。 在此处输入图片说明

到目前为止,我的代码:

package binarysearch;

import java.io.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class Binarysearch {

public static void main(String[] args) throws IOException {

    BufferedReader reader = new BufferedReader(new FileReader("quotes.txt"));

    ArrayList list = new ArrayList();
    String str = null;

    //Getting all of the input from the textfile
    while ((str = reader.readLine()) != null) {
        list.add(str); //Getting all of the lines of the textfile
    }

    String array[] = new String[list.size()];
    list.toArray(array);

    String num = JOptionPane.showInputDialog("What quote number would you like to see? (1 - 99)");
    System.out.println("Searching: " + num  + "  "+ binarySearch(array, 0, array.length - 1, num));
}

public static boolean binarySearch(String myArray[], int left,
        int right, String num) {
    //Temporary print for learning purposes
    System.out.print("Searching array: ");
    for (int i = left; i <= right; i++) {
        System.out.print("[" + myArray[i] + "]");
    }
    System.out.println(" for " + num);
    //end temporary print

    int middle;
    if (left > right) {
        return false;
    }
    middle = (left + right) / 2;
    if (myArray[middle].equals(num)) {
        return true;
    }
    if (num.compareTo(myArray[middle]) > 0) {
        return binarySearch(myArray, left, middle - 1,
                num);
    } else {
        return binarySearch(myArray, middle + 1, right,
                num);
    }
}
}

我有的文本文件:

1
quote 1
2
quote 2
4
quote 3
7
quote 4
8
quote 5
12
quote 6
16
quote 7
18
quote 8
22
quote 9
23
quote 10

您可能会得到错误的信息,因为当检查用户的数字是否高于或低于中位数时,有时它会落在实际报价的索引中。 索引将在报价编号上还是实际报价上(取决于输入的编号),因此即使存在索引,您也会得到错误。 您可以在仅包含引号的方法中创建一个新数组,也可以对其进行更改以忽略包含引号的奇数索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM