插入已排序的数组,无法插入第3个元素。

时间:2015-11-17 03:06:13

标签: java arrays sorting object

这是我的数据结构和算法分配。我将创建一个按名称排序的学生对象数组。我的问题在于我的插入算法。它将新学生姓名与数组中的名称进行比较,并找到小于studentArray [i]且大于sudentArray [i-1]的位置。这段代码只有在数组中已经存在至少3个元素时才能工作,要插入前三个我需要找出不同的方法,我能够得到第一个和第二个。但是,我在那里获得第三个,并在数组中移动元素以保持排序时遇到了麻烦。这是到目前为止插入的代码。

 public boolean insert2(StudentListing newStudent) {
    int low = 0;
    int high = next - 1;
    int i = (low + high) / 2;
    System.out.println("high is " + high + ", i is " + i + ", next is " + next);

    if(next == 0) {
        System.out.println("No students in array");
        studentArray[i] = newStudent;
        next = next + 1;
        numberOfStudents++;
        return true;
    }

    while(numberOfStudents < 3) {
        while(numberOfStudents == 1) {
            if(newStudent.getName().compareTo(studentArray[i].getName()) > 0) {  //If new student is smaller than student in current index i
                studentArray[next] = newStudent;
                next = next + 1;
                numberOfStudents++;
                return true;
            }
            else {  //new student's name is larger than students name in current index i
                studentArray[next] = studentArray[i];
                studentArray[i] = newStudent;
                next = next + 1;
                numberOfStudents++;
                return true;
            }
        while(numberOfStudents == 2) {
                if(newStudent.getName().compareTo(studentArray[i].getName()) < 0)
        }

    }

    while(studentArray[i] != null && !(newStudent.getName().compareTo(studentArray[i].getName()) > 0) && 
        newStudent.getName().compareTo(studentArray[i-1].getName()) < 0 && !(i >= next) && low >= high) {
        System.out.println("high is " + high + ", i is " + i + ", next is " + next);
        if(newStudent.getName().compareTo(studentArray[i].getName()) > 0) 
            {   System.out.println("newStudent is smaller");
                high = i - 1; }
        else {  System.out.println("newStudent is larger");
                low = i + 1; }
        i = (high + low) / 2;
    }
    System.out.println("high is " + high + ", i is " + i + ", next is " + next);
    System.out.println("Finished binary search");
    for(int j = next; j >= i; j--) {
        System.out.println("J is " + j);
        studentArray[j] = studentArray[j-1];
    }
    next = next + 1;
    studentArray[i] = newStudent.deepCopy();
    return true;
}

0 个答案:

没有答案