java - 尝试对对象数组进行二分搜索 [比较器]

标签 java binary comparator binary-search comparable

我已经努力尝试编写这段代码几天了。基本上,我们必须根据 Student 数组中可比较的“Student”对象的 SSN 执行二分搜索。在 SSN 上执行二进制搜索后,应打印出与该 SSN 的名字和姓氏相关联的学生以及该学生的职位/地点。我遇到的问题是,当我执行二进制搜索来查找学生的位置/位置时,它总是返回“-1”,而不是学生的元素位置。有什么帮助吗?

学生类

package binarySearch;

public class Student implements Comparable<Student>{

    private String firstName, lastName, SSN, bankAccount;



    public Student(String first, String last, String ssn, String bkacct) {

        this.firstName = first;
        this.lastName = last;
        this.SSN = ssn;
        this.bankAccount = bkacct;

    }   

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }


    public String getSSN() {
        return SSN;
    }

    public String getBankAccount() {
        return bankAccount;
    }



    //toString method
    public String toString() {
        return "Employee: [FirstName = " + firstName + ", LastName = " + lastName + ", SSN = " + SSN + ", BankAccount = "
                    + bankAccount + "]";
        }

    public boolean equals(Object other) {

        return (lastName.equals(((Student)other).getLastName()) &&
                firstName.equals(((Student)other).getFirstName())&&
                SSN.equals(((Student)other).getSSN()) && 
                bankAccount.equals(((Student)other).getBankAccount()));
        }


    //Sorting the array based on SSN
    public int compareTo(Student key) {

        return SSN.compareTo(key.getSSN());



    }

}

我在哪里对二进制搜索的数组进行排序

package binarySearch;

public class ObjectBubbleSorter {
    public static void bubbleSort(Comparable[] array) {

        int lastPos;
        int index;
        Comparable temp;

        for(lastPos = array.length-1; lastPos >= 0; lastPos -= 1) {
            for(index = 0; index <= lastPos - 1; index+=1) {

                if(array[index].compareTo(array[index+1]) > 0) {

                    temp = array[index];
                    array[index] = array[index+1];
                    array[index+1] = temp;

                }       
            }

        }

    }

}

以及我执行二进制搜索的位置

package binarySearch;


public class ObjectBubbleSortTest {

    public static int binarySearch(Student list[], Student key) {

        int low = 0;
        int high = list.length - 1;
        int middle = (low + high + 1)/2;
        int location = -1;

        while((low <= high) && (location == -1)){

            if (list[middle].equals(key)) { //location current middle

                location = middle;

            }
            else if(list[middle].compareTo(key) < 0 ) { //middle too high
                high = middle - 1;
            }

            else {
                low = middle + 1;
            }

            middle = (low + high + 1)/2;
        }

        return location;
    }


    public static void main(String[]args) {


        Student[] student = new Student[5];

        //order: First Name, Last Name, SSN, Bank_Account_Number 
        student[0] = new Student("Adam", "Sarrone", "1234567", "9022345"); 
        student[1] = new Student("Ryan", "Petrowvoksi", "4345123", "0120345"); 
        student[2] = new Student("Jenn", "Henderson", "8124512", "564214"); 
        student[3] = new Student("Ricky", "Jean", "3512345", "612345");
        student[4] = new Student("Dare", "Ogun", "421451", "198213");

        System.out.println("Original array order: \n");
        for (Student element : student) 
            System.out.print(element + "\n");


        //sorting array
        ObjectBubbleSorter.bubbleSort(student);

        System.out.println();

        System.out.println("\nSorted array order: \n");
        for (Student element : student) 
            System.out.print(element + "\n");

        System.out.println();

        //creating student obj
        Student student1 = new Student("Ryan", "Petrowvoksi", "4345123", "0120345"); 


        int studentSSN = binarySearch(student, student1);
        System.out.print(studentSSN);

        System.out.print(student1.getFirstName() + " " + student1.getLastName() + " was found at position: " + studentSSN);

    }

当我执行该二元搜索时,它总是返回 -1 而不是学生元素位置

最佳答案

更改此行list[middle].compareTo(key) < 0进入list[middle].compareTo(key) > 0里面binarySearch while 循环。

看来你的compareTo功能的工作方式与您希望的相反。

顺便说一句,我建议您将 binarySearch 更改为更具可读性的搜索:

public static int binarySearch(Student list[], Student key) {
        int low = 0;
        int high = list.length - 1;
        int middle;
        int location = -1;

        while (low <= high) {
            middle = (low + high + 1) / 2;
            int compare = list[middle].compareTo(key);
            if (compare == 0) {
                location = middle;
                return location;
            } else if (compare > 0) {
                high = middle - 1;
            } else {
                low = middle + 1;
            }
        }
        return location;
}

关于java - 尝试对对象数组进行二分搜索 [比较器],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61431109/

相关文章:

java - 导入 com.sybase.jdbc4.jdbc.*;错误

java - 在Java中将Base64转换为二进制字符串

python - 将数字转换为 4 字节的二进制?

java - 随后按字段对对象进行排序

java - 按下按钮时退出 fragment 或 Activity

Java 游戏循环(绘画)卡住了我的窗口

java - 标准差不传递?

java - 泛型、比较器和 Map 排序时出现问题

java - double 格式设置为不包含小数位

c++ - 将 struct 写入文件时写入了太多字节