javaloopsbinary-search-treebufferedreaderfilereader

there is an "endless loop" how ı can fix it


this code is creating a loop , The variable named "Number of students" is constantly increasing. I couldn't find where the problem is. {1.14,1.49,1.54,1.86,2.04,2.19,2.86,3.02,3.16} when I output this it should return 1

public class Main {

public static void main(String[] args) {
  int ogrenciSayisi=0;
     if (Student.readCSV("siraliogrenci.txt").length!=0) {
         Student[] student = Student.readCSV("siraliogrenci.txt");
        int alt_indis=0;
        int ust_indis=student.length-1;
        int orta_indis;
        
        while(alt_indis<=ust_indis){
            orta_indis=(alt_indis+ust_indis)/2;
            if (student[orta_indis].getGPA()==3.02) {
                ogrenciSayisi++;
                int solIndis = orta_indis-1;
                int sagIndis = orta_indis+1;
                while (solIndis>=0 && student[solIndis].getGPA()==3.02) {                        
                    ogrenciSayisi++;
                    solIndis--;
                }
                while (sagIndis<student.length && student[sagIndis].getGPA()==3.02) {                        
                    ogrenciSayisi++;
                    sagIndis++;
                } 
            }
            else if(student[orta_indis].getGPA()<3.02){
                alt_indis=orta_indis+1;
            }
            else{
                ust_indis=orta_indis-1;
            }
        }
        
    }
     System.out.println(ogrenciSayisi);
    

}

}


Solution

  • I believe you are trying to do a binary search here on 3.02. The problem seems to be in if (student[orta_indis].getGPA()==3.02). Inside this if condition, you are not updating alt_indis and ust_indis. So once it reaches where its 3.02, for every further iteration of while loop it keeps using same alt_indis and ust_indis; thus using same orta_indis (orta_indis=(alt_indis+ust_indis)/2;) causing an infinite loop. To remedy this you should update either your alt_indis and ust_indis or break out of the loop from inside if based on some condition.