我找到了一些可用于对整数数组执行二进制搜索的代码,我正在尝试更改它,以便我可以在字符串数组上使用它。
这是我到目前为止所做的:
import edu.princeton.cs.introcs.In;
import edu.princeton.cs.introcs.StdIn;
import edu.princeton.cs.introcs.StdOut;
import java.util.Arrays;
public class BinarySearch {
/**
* This class should not be instantiated.
*/
private BinarySearch() { }
/**
* Searches for the integer key in the sorted array a[].
* @param key the search key
* @param a the array of integers, must be sorted in ascending order
* @return index of key in array a[] if present; -1 if not present
*/
public static int rank(String key, String[] a) {
int lo = 0;
int hi = a.length - 1;
int steps = 0;
while (lo <= hi) {
steps = steps + 1; // this will keep count of the number of steps needed
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid])
{
hi = mid - 1;
}
else if (key > a[mid])
{
lo = mid + 1;
}
else return mid;
}
return steps;
}
/**
* Reads in a sequence of integers from the whitelist file, specified as
* a command-line argument. Reads in integers from standard input and
* prints to standard output those integers that do *not* appear in the file.
* @param args
*/
public static void main(String[] args) {
// read the integers from a file
In in = new In("C:\\Users\\Owner\\Desktop\\EnglishWordList.txt");
String[] whitelist = in.readAllStrings();
// sort the array
Arrays.sort(whitelist);
// read integer key from standard input; print if not in whitelist
while (!StdIn.isEmpty()) {
String key = StdIn.readString();
if (rank(key, whitelist) == -1)
StdOut.println(key);
}
}
}
我在两个if语句的rank()方法中遇到错误。它声明我不能使用运算符&#34;&lt;&#34;和&#34;&gt;&#34;对于字符串,意味着它不看ASCII码。我该如何解决这个问题?可能还有其他问题,但这是我的IDE唯一突出的问题。请让我知道你的想法。
答案 0 :(得分:1)
您可以使用a.compareTo(b)
,即使用可比较的界面,而不是使用>
或<
运算符。
可比较的界面。比较值并返回一个int,它告诉值是否比较小于,等于或大于。如果您的类对象具有自然顺序,请实现Comparable接口并定义此方法。所有具有自然排序的Java类都实现了这一点(String,Double,BigInteger,...)。
答案 1 :(得分:1)
请尝试使用以下算法
public boolean binarySearch(int key, int[] arrayToSearch) {
if (arrayToSearch.length == 0) {
return false;
}
int low = 0;
int high = arrayToSearch.length - 1;
while (low <= high) {
int midItem = (low + high) / 2;
if (key > arrayToSearch[midItem]) {
low = midItem + 1;
} else if (key < arrayToSearch[midItem]) {
high = midItem - 1;
} else { // The element has been found
return true;
}
}
return false;
}
答案 2 :(得分:0)
试试这个,它也适用于字符串
public static String binarySearch(String[] names, String x) {
int high = names.length - 1;
int low = 0;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (names[mid].compareTo(x) == 0) {
return names[mid];
}
else if (names[mid].compareTo(x) > 0) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return null;
}