2017-03-08 17 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

これは静的(グローバル)変数が意味をなさせる場合の1つです。これにより、インターフェース(呼び出しパラメーター)を変更せずにコードをプロファイルすることができます。テストが完了したら、簡単に削除することができます。コメントとして、静的変数をパラメータとして渡したい場合は、Javaがプリミティブ型をサポートしていない参照渡しを渡す必要があります。したがって、以下のように、渡すにはクラス/オブジェクトを作成する必要があります参照により。 – rcgldr

答えて

0

あなたが直面している問題は、関数が戻った後、その値を見れば関数に渡されたときにint型のようなプリミティブ型のJavaの値に関数内でそれらに加えた変更を反映していないということです。この問題を回避する方法は、必ずしも「良いスタイル」ではないにもかかわらず、プリミティブオブジェクトではなくクラスオブジェクトを関数に渡してから、関数内で作成されたクラスオブジェクトのメンバ変数に変更を加えます後で外に反映される。

// 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 ... 
} 
関連する問題