gpt4 book ai didi

java - java中使用MergeSorter的问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:39 24 4
gpt4 key购买 nike

我正在研究这个合并排序器,但有一些东西不起作用,我无法弄清楚。任何帮助表示赞赏。谢谢。问题很可能出在排序方法中。

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 . .

我很感激任何帮助。谢谢

最佳答案

您的合并方法存在错误。检查以下示例。使用参数 merge(0,2,4) 和 a = {5,6,7,1,2} 运行方法 merge。您将得到 = {1,2,7,5,6}。

关于java - java中使用MergeSorter的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9782326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com