如何实现字符串数组的二进制搜索?

时间:2016-05-21 12:36:27

标签: java algorithm binary-search

我做了一些研究但没有找到任何东西,但如果这是重复的,请告诉我。

我有这个代码用于整数二进制搜索

package thepac;

public class CustomBS{

public static void main(String[] args){
    int[] listOfNumbers = new int[]{2,45,65,76,89,100,342,455};
    int numberToSearch = 100;
    int lowestIndex = 0;
    int highestIndex = listOfNumbers.length-1;
    int middleIndex;

    while(lowestIndex<=highestIndex){
        middleIndex = (lowestIndex+highestIndex)/2;

        if(numberToSearch > listOfNumbers[middleIndex]){
            lowestIndex = middleIndex+1;
        }else if(numberToSearch < listOfNumbers[middleIndex]){
            highestIndex = middleIndex-1;
        }else{
            break;
        }
    }//end of while
    if(lowestIndex > highestIndex){
        System.out.println("not found");
    }else{
        System.out.println("found");
    }
}
}

这可以找到,我理解这个概念。是否有可能实现一个版本的搜索字符串数组中的字符串?

我想不出如何实现这个,因为当前算法检查被搜索的数字是高于还是低于中间索引,但如果它是一个字符串,我该如何检查它是否高于或低于另一个字符串?

我知道我可以使用String.compareTo()方法来检查字符串是大于还是短于另一个字符串,但我不确定这是否是实现此方法的正确方法。

1 个答案:

答案 0 :(得分:4)

如果您有两个字符串s1s2,那么

s1.compareTo(s2) 
如果s1按字典顺序小于s2,则

会返回否定结果;如果s1按字典顺序大于s2,则返回肯定结果;如果public static void main(String[] args){ String[] listOfStrings = new String[]{"a","b","c","d","g","h","k","z"}; String stringToFind = "d"; int lowestIndex = 0; int highestIndex = listOfStrings.length-1; int middleIndex = 0; while(lowestIndex<=highestIndex){ middleIndex = (lowestIndex+highestIndex)/2; if(stringToFind.compareTo(listOfStrings[middleIndex]) > 0){ lowestIndex = middleIndex+1; }else if(stringToFind.compareTo(listOfStrings[middleIndex]) < 0){ highestIndex = middleIndex - 1; }else{ break; } }//end of while if(lowestIndex > highestIndex){ System.out.println("not found"); }else{ System.out.println("found at " + middleIndex); } } 相等,则返回0。

所以你可以这样编写你的函数:

        int m;
        int n; static Fraction fraction = new Fraction();//edited
        int denominator;
        int numerator;
        Fraction[] frac;//fraction
        string l = Console.ReadLine();
        string[] split = l.Split(' ');
        m = Int32.Parse(split[0]);
        n = Int32.Parse(split[1]);
        frac = new Fraction[m];
        for (int i = 0; i < m; i++)
        {
            string o = Console.ReadLine();
            string[] split2 = o.Split(' ');
            denominator= Int32.Parse(split2[0]);
            numerator= Int32.Parse(split2[1]);
            fraction.denominator= denominator;
            fraction.numerator= numerator;
            frac[i] = fraction;//put the numbers in the
                               //array
        }
        if (m < n)
            SelectionSort(frac);
        else
            QuickSort(frac, 0, m - 1);

        for (int i =0; i< m; i++)
        {
            Console.WriteLine(frac[i]);
        }