Search code examples
javaindexoutofboundsexceptionquicksort

quicksort going out of bound


I know that there are other question about this, but nobody has my implementation of quicksort so I need your help to fix this.

Here is my quicksort:

    //u is first index (0) and v is last (numberOfPatients - 1)
public void quickSort(Patient arrayPatients[], int u, int v) { 
    int q;

    if(u == v) return;  
    q = perno(arrayPatients, u, v);

    if(u < q) quickSort(arrayPatients, u, q-1); 
    if(q < v) quickSort(arrayPatients, q+1, v);
}


public int perno(Patient arrayPatients[], int first, int last){
    Patient temp = new Patient();
    int i = first;
    int j = last + 1;
    long pivot = arrayPatients[first].priority;

    while(i < j){
        do i++;
        while(arrayPatients[i].priority <= pivot && i<= last);  //Line 1441
        do j--; 
        while(arrayPatients[j].priority > pivot && j >= first);
        if(i < j){  
            //Swap arrayPatients[i] and arrayPatients[j]
            temp = arrayPatients[i];
            arrayPatients[i] = arrayPatients[j];
            arrayPatients[j] = temp;
        }
    }
    //Swap arrayPatients[first] and arrayPatients[j]
    temp = arrayPatients[first];
    arrayPatients[first] = arrayPatients[j];
    arrayPatients[j] = temp;
    return j;
}

edit: I have 4 patients, this is the error I get:

java.lang.ArrayIndexOutOfBoundsException: 4
    at sorter.Sort.perno(Sort.java:1441)
    at sorter.Sort.quickSort(Sort.java:1425)
    at sorter.Sort.quickSort(Sort.java:1428)
    at sorter.Sort.sorting(Sort.java:851)
    at sorter.Home$27.run(Home.java:1314)

I've added a comment with the number of the incriminated line


Solution

  • Your problem is most likely due to checking array at index first, then checking if the index is within bounds at all.

    Instead:

        do i++;
        while(arrayPatients[i].priority <= pivot && i<= last);  //Line 1441
        do j--; 
        while(arrayPatients[j].priority > pivot && j >= first);
    

    Try:

        do i++;
        while(i<= last && arrayPatients[i].priority <= pivot);  //Line 1441
        do j--; 
        while(j >= first && arrayPatients[j].priority > pivot);
    

    and see if that helps.