我正在研究这个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 . .
我感谢任何帮助。谢谢
答案 0 :(得分:1)
您在合并方法中存在错误。检查以下示例。 运行方法与参数merge(0,2,4)和a = {5,6,7,1,2}合并。你会得到一个= {1,2,7,5,6}。