2017-03-08 58 views
1

我已经写了一个快速排序程序,该程序计算按照升序对数组排序进行的交换次数。在这个程序中,我使用了一个全局变量来计算交换次数,因为我无法确定如何通过多个递归级别保留值。我理解这个概念,即当函数自我折叠时,通过传递多级递归来保留该值,但我显然无法实现它。有人可以建议我这样做吗?如何通过多个递归级别保留一个值?

import java.util.Scanner; 

public class QuickSort { 

    // global variable for counting the quicksort shifts. 
    private static int swapCount = 0; 

    public static void main(String[] args) { 

     // scanning the values; 
     Scanner scan = new Scanner(System.in); 
     int N = scan.nextInt(); 
     int ar[] = new int[N]; 
     for(int i = 0 ; i < N ; i++){ 
      int value = scan.nextInt(); 
      ar[i] = value; 
     } 

     quickSort(ar, 0, ar.length-1); 
     System.out.println(swapCount); 

    } 

    //quickSort 
    public static void quickSort(int ar[], int start, int end){ 

     if(start<end){ 
      int pIndex = partition(ar, start, end); 
      quickSort(ar,start, pIndex-1); 
      quickSort(ar, pIndex+1, end); 
     } 
    } 

    // partition function 
    public static int partition(int ar[], int start, int end){ 
     int pivot = ar[end]; 
     int pIndex = start; 
     for (int i = start ; i < end ; i++){ 
      if(ar[i] < pivot){ 
       int temp = ar[i]; 
       ar[i] = ar[pIndex]; 
       ar[pIndex] = temp; 
       swapCount++; 
       pIndex++; 
      } 
     } 
     int temp = ar[end]; 
     ar[end] = ar[pIndex]; 
     ar[pIndex] = temp; 
     swapCount++; 
     return pIndex; 
    } 
} 
+1

您可以将包含该值的对象传递给调用堆栈。这可能是一个专门的类,或者简单的'int []'。 –

+0

这是静态(全局)变量可能有意义的一种情况。它允许你在不改变接口的情况下调用代码(调用参数)。测试完成后,您可以轻松地将其删除。正如所评论的,如果您确实想要将静态变量作为参数传递,您必须通过引用来传递它,而Java不支持基本类型,所以在下面的回答中,您必须创建一个类/对象才能通过引用。 – rcgldr

回答

0

你所面临的问题是,在基本类型如int的Java的值时,传递给函数,如果你的函数返回后看看他们的价值没有反映他们提出的函数中的任何改变。解决这个问题的方法,即使它不一定是“好风格”,但是要将一个Class对象传递给该函数而不是一个原始对象,然后更改该函数内部的类对象的成员变量稍后在外面反映。

// in main() 
Integer nbrSwaps = new Interger(0); 
quickSort(ar, 0, ar.length-1, nbrSwaps); 

//quickSort 
public static void quickSort(int ar[], int start, int end, Integer swapCount) { 

    if(start<end){ 
    int pIndex = partition(ar, start, end, swapCount); 
    quickSort(ar,start, pIndex-1, swapCount); 
    quickSort(ar, pIndex+1, end, swapCount); 
    } 
} 

// partition function 
public static int partition(int ar[], int start, int end, Integer swapCount) { 
    ... as before ... 
}