2012-03-20 11 views
1

私はこのMergeSorterに取り組んでいますが、機能しないものがあり、わかりません。どんな助けもありがとうございます。ありがとうございました。問題はソート方法にある可能性が最も高いです。JavaでMergeSorterを使用する際の問題

public class MergeSorter 
{ 
private int[] a; 

/** 
    Constructs a merge sorter. 
    @param anArray the array to sort 
*/ 
public MergeSorter(int[] anArray) 
{ 
    a = anArray; 
} 

/** 
    Sorts the array managed by this merge sorter. 
*/ 
public void sort() 
{ 
    int size = 1; 
    int from = 0; 
    int to = a.length - 1; 

    // Complete this for the draft 
    while (size < to - from) 
    { 
    for (int i = 0; i<=a.length; i=i+size*2) //for (int i = 0; i<a.length; i=i+size*2) 
    { 
     if(a.length>i+size*2-1){ 
      merge(i, i+size-1, i+size*2-1); 
     } 
     else if(a.length>i+size){ 
      merge(i, i+size-1, a.length-1); 

     } 
    } 
    size = 2 * size; 
    } 
} 

public void merge(int from, int mid, int to) 
{ 
    System.out.println("Merging " + from + "..." + mid 
+ " and " + (mid + 1) + "..." + to); 

    // Complete this method for the final submission 
    int iFirst = from; // Next element to consider in the first array 
    int iSecond = mid+1; // Next element to consider in the second array 
    int temp = 0; 

    // As long as neither iFirst nor iSecond is past the end, move 
    // the smaller element into a 
    while (iFirst <= mid && iSecond <= to) 
    { 
    if (a[iFirst] < a[iSecond]) 
    { 
     iFirst++; 
    } 
    else if (a[iFirst] > a[iSecond]) 
    { 
     temp = a[iFirst]; 
     a[iFirst] = a[iSecond]; 
     a[iSecond] = temp; 
     iSecond++; 
    } 
    } 
} 
} 

そして、これが

public class test { 
public static void main(String[] args){ 
int[] a = {0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19}; 
    MergeSorter m = new MergeSorter(a); 
    m.sort(); 
    for(int b : a){ 
     System.out.print(b + " "); 
    } 
} 
} 

私のテスターであり、これが出力されているが、問題は、番号が連続していない最後の行です。

Merging 0...0 and 1...1 
Merging 2...2 and 3...3 
Merging 4...4 and 5...5 
Merging 6...6 and 7...7 
Merging 8...8 and 9...9 
Merging 10...10 and 11...11 
Merging 12...12 and 13...13 
Merging 14...14 and 15...15 
Merging 16...16 and 17...17 
Merging 18...18 and 19...19 
Merging 0...1 and 2...3 
Merging 4...5 and 6...7 
Merging 8...9 and 10...11 
Merging 12...13 and 14...15 
Merging 16...17 and 18...19 
Merging 0...3 and 4...7 
Merging 8...11 and 12...15 
Merging 0...7 and 8...15 
Merging 0...15 and 16...19 
0 1 2 3 4 5 6 7 8 9 12 13 14 15 16 17 10 11 18 19 Press any key to continue . . 

何か助けていただきありがとうございます。ありがとうございます

答えて

1

マージメソッドにバグがあります。次の例を確認してください。 パラメータmerge(0,2,4)とa = {5,6,7,1,2}でメソッドをマージします。 = {1,2,7,5,6}を得るでしょう。

関連する問題