I
I
Ilya2020-11-09 01:28:58
Java
Ilya, 2020-11-09 01:28:58

Why does nothing happen after sorting?

Did sorting of an array of objects of class Student. Insertion sort worked correctly, but I ran into a problem with quick sort. The program stops after student.quickSort(0, 4) in main, or rather it starts typing into the console, and it's not clear why.

import java.util.Scanner;

public class SortingStudentsByGPA {
    Student[] iDNumber = new Student[5];

    public void setArray() {
        for (int i = 0; i < iDNumber.length; i++) {
            Scanner in = new Scanner(System.in);
            System.out.print("Student: ");
            String name = in.nextLine();
            System.out.print("Grade: ");
            int grade = in.nextInt();
            iDNumber[i] = new Student(name, grade);
        }
    }

    public void quickSort(int low, int high) {
        if (iDNumber.length == 0) {
            return;
        }
        if (low >= high) {
            return;
        }

        int middle = low + (high - low) / 2;
        Student base = iDNumber[middle];

        int i = low;
        int j = high;
        while (i <= j) {
            while (iDNumber[i].compareTo(base) < 0) {
                i++;
            }
            while (iDNumber[i].compareTo(base) > 0) {
                j--;
            }
            if (i <= j) {
                Student temp = iDNumber[i];
                iDNumber[i] = iDNumber[j];
                iDNumber[j] = temp;
                i++;
                j--;
            }
        }
        if (low < j) {
            quickSort(low, j);
        }
        if (high > i) {
            quickSort(i, high);
        }
    }

    public void outStudents() {
        for (Student student : iDNumber) {
            System.out.println(student);
        }
    }

    public static void main (String[] args){
        SortingStudentsByGPA student = new SortingStudentsByGPA();
        student.setArray();
        student.quickSort(0, 4);
        student.outStudents();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Carp, 2020-11-09
@Avlordin

you indicated instead of the desired j - "i"

public void quickSort(int low, int high) {
 while (iDNumber[j].compareTo(base) > 0) {
                j--;
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question