繁体   English   中英

快速排序 integer arrays 的数组

[英]quick sorting an array of integer arrays

我需要对 integer arrays 的数组进行排序,以解决我的一个课程中的作业问题。 我似乎几乎每次都会收到 StackOverFlowError 。 我的数组是 list2[10][10]。 我的快速排序分为 3 种方法。 quickSort1(int, int) 是主要的 function,partition 比较一个新的 partition,swap 简单地交换了 integer arrays] 和 list2[j]。 如果 list2[a] 小于 list2[b],compare(int a, int b) 方法返回 1 - 如果 b 小于 a,则返回 1,如果它们相等,则返回 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];
    }

}

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

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

尝试从您的代码中删除它们。

导入 java.util.Arrays; 导入 java.util.Scanner;

公共 class 苹果 {

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);
    }







}

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM