나는 배열을 오름차순으로 정렬하기 위해 수행 된 스왑의 수를 계산하는 빠른 정렬 프로그램을 작성했습니다. 이 프로그램에서는 여러 단계의 재귀를 통해 값을 유지하는 방법을 설명 할 수 없기 때문에 전역 변수를 사용하여 스왑 수를 계산했습니다. 필자는 함수가 자체적으로 접혀있을 때 여러 수준의 재귀를 통과하여 값을 유지한다는 개념을 이해하지만 분명히 구현할 수는 없습니다. 누군가 제게 그것을 할 수있는 방법을 제안 할 수 있습니까?여러 수준의 재귀를 통해 값을 유지하는 방법은 무엇입니까?
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