Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

quick sorting an array of integer arrays

I need to sort an array of integer arrays for a homework problem in one of my classes. I seem to get a StackOverFlowError almost every time. My array is list2[10][10]. My quick sort is separated into 3 methods. quickSort1(int, int) is the main function, partition compares a new partition, and swap simply swaps the integer arrays at list2[i] and list2[j]. the compare(int a, int b) method returns 1 if list2[a] is smaller than list2[b] - 1 if b is smaller than a and 100 if they are equal.

I'm not sure my quick sort is implemented correctly but I know swap and compare work exactly how I say they do. I have a hunch that it mostly recurs forever when I get the StackOverFlowError.

public static int partition(int low, int high)
{
      int i = low, j = high;
      int pivot = (low+high)/2;
          System.out.println(i + " " + j + " " + pivot);
      while (i <= j) {
            while (compare(i, pivot) > 0)
                  i++;
            while (compare(pivot, j) > 0)
                  j--;
            if (i < j) {
                  swap(i,j);
                  i++;
                  j--;
            }
                if (i == pivot && i == j-1)
                {
                    return i;
                }
                if (j == pivot && j-1 == i)
                {
                    return i;
                }
      }

      return i;
}

public static void quickSort1(int low, int high) {
        System.out.println("Recursion: " + recursions);
        int i = partition(low, high);
        System.out.println(i);
        if (low < i -1)
        {
            recursions++;
            quickSort1(low, i -1);
        }
        if (i < high-1)
        {
            recursions++;
            quickSort1(i, high);
        }


}

public static void swap( int i, int j)
{
    int[] temp = new int[n];

    for(int k = 0; k < n; k++) {
    temp[k] = list2[i][k];
    }
    for(int k = 0; k < n; k++) {
    list2[i][k] = list2[j][k];  
    }
    for(int k = 0; k < n; k++) {
    list2[j][k] = temp[k];
    }

}
like image 811
Sean Avatar asked Jan 30 '26 13:01

Sean


1 Answers

I don't think these lines are necessary inside the loop while(i <= j):

if (i == pivot && i == j-1)
{
    return i;
}
if (j == pivot && j-1 == i)
{
    return i;
}

Try removing them from your code.

like image 185
Sachin Joseph Avatar answered Feb 01 '26 01:02

Sachin Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!