LinkedList的二进制搜索

时间:2014-05-06 21:47:20

标签: java

我正在尝试对已排序的链接列表中的节点执行二进制搜索。我不仅在努力使用我无法看到的算法来解决while循环问题。我使用compareto()方法来查找列表中的项目。除了这种方法,程序的其余部分工作正常。任何帮助或建议将不胜感激。

public void contNameBinSearch()
{
    int beg = 0;  
    int mid = (contTable.size()/2);
    int end = contTable.size()-1;
    int binFind;
    String findBin;
    boolean findBinName = false;

    System.out.print("Please enter contributor's last name for binary search: \r\n");
    Scanner sn = new Scanner(System.in);
    findBin = sn.nextLine();
    System.out.println();

    findBinName = contTable.get(mid).getLastName().equalsIgnoreCase(findBin);

    binFind = findBin.compareTo(contTable.get(mid).getLastName()); 

    System.out.print("initial beg " + beg + "\r\n");
    System.out.print("initial mid " + mid + "\r\n");
    System.out.print("initial end " + end + "\r\n");    

    while (findBinName = false)
    {
        System.out.print("Test Point 1");

        if (binFind == 0) 
             {
                 System.out.print("Test Point 2");
                 findBinName = true;
                 break;
             }

        else if (binFind > 0)
             {
                 System.out.print("Test Point 3");
                 mid = end -(end - mid)/2;
                 end = mid + mid/2;
             } 

        else if (binFind < 0)
             {
                 System.out.print("Test Point 4");
                 end = mid;
                 mid = mid/2;                     
             } 

    }

        if (findBinName)
             {   
                 System.out.print(contTable.get(mid).getData() + "\r\n");
             }
        else
             {
                 System.out.print("User " + findBin + " does not exist please try again.\r\n\r\n");
                 contNameBinSearch();
             }

     System.out.println();
}

1 个答案:

答案 0 :(得分:0)

改变这个:

while (findBinName = false)

while (findBinName == false)

甚至更好

while (!findBinName)

在以前的版本中,将值false分配给findBinName,然后测试findBinName的值,但它已经是假的。所以你的循环永远不会执行。