快速排序整数数组的数组

时间:2011-07-22 14:38:09

标签: java arrays sorting

我需要为我的一个类中的作业问题排序一个整数数组数组。我似乎几乎每次都得到一个StackOverFlowError。我的数组是list2 [10] [10]。我的快速排序分为3种方法。 quickSort1(int,int)是主函数,分区比较新分区,交换只是交换list2 [i]和list2 [j]中的整数数组。如果list2 [a]小于list2 [b],则compare(int a,int b)方法返回1,如果b小于a,则返回1,如果b等于,则返回100。

我不确定我的快速排序是否正确实现但我知道交换和比较工作正是我说他们做的。我有一种预感,当我得到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];
    }

}

2 个答案:

答案 0 :(得分:1)

我不认为这些行在循环while(i <= j)中是必要的:

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

尝试从代码中删除它们。

答案 1 :(得分:0)

import java.util.Arrays; import java.util.Scanner;

public class apples {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the number of the values");
    int num = input.nextInt();
    int a[] = new int [num];
    System.out.println("Enter the nambers now");
    for(int i=0; i<a.length; i++){
        a[i] = input.nextInt();
    }
    Arrays.sort(a);
 int min =a[0];
System.out.println("The minmum value is    "+min);
int max= a[a.length-1];
System.out.println("The maxemum value is   "+max);
int d = max-min;
System.out.println("the difrentc between the max and the min is "+  d);

    System.out.println("The Arrays R \t");
    for(int g=0; g<=a.length;g++){
        int m = a[g];
        System.out.println(m);
    }







}

    }