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;
}
}
您可以将包含该值的对象传递给调用堆栈。这可能是一个专门的类,或者简单的'int []'。 –
这是静态(全局)变量可能有意义的一种情况。它允许你在不改变接口的情况下调用代码(调用参数)。测试完成后,您可以轻松地将其删除。正如所评论的,如果您确实想要将静态变量作为参数传递,您必须通过引用来传递它,而Java不支持基本类型,所以在下面的回答中,您必须创建一个类/对象才能通过引用。 – rcgldr