您好我一直在努力让合并排序正常工作,我有一个完整的代码但是没有得到正确的结果......这是我的代码,结果是" 876323149"任何帮助将不胜感激。
public class MergeSort
{
private static int[] local; // for use in copying
private static int[] a;
public static void main(String[] args)
{
int[] test = {2,3,1,4,7,8,6,3,9};
sort(test);}
public static void sort(int[] orig)
{
int n = orig.length;
local = new int[n];
a = orig;
recursiveSort(0, n-1);
for(int i = 0; i < a.length; i ++){
System.out.print(a[i]);
}
}
private static void recursiveSort(int lo, int hi)
{
int mid =(hi + lo) / 2;
if(hi-lo > 2){
recursiveSort(lo, mid);
recursiveSort(mid + 1, hi);
merge(lo, mid + 1, hi);
}
}
private static void merge(int lo, int mid, int hi)
{
int d = lo;
int b = mid + 1;
int c = lo;
for (int i = lo; i <= hi; i++) {
local[i] = a[i];
}
while(d <= mid && b <= hi){
if(local[d] > local[b]){
a[c] = local[d];
d++;}
else{
a[c] = local[b];
b++;}
c++;}
while (d <= mid) {
a[c] = local[d];
c++;
d++;
}
}
}
答案 0 :(得分:0)
你必须确保lo小于hi,以便recursiveSort继续递归地对不同的数组进行排序,并且不会尝试对长度为&lt; = 1的数组进行排序。更重要的是,mid必须设置在每次调用if语句时都会使用if语句
以下是修复:
private static void recursiveSort(int lo, int hi)
{
if(lo < hi){
int mid =(hi + lo) / 2;
recursiveSort(lo, mid);
recursiveSort(mid + 1, hi);
merge(lo, mid + 1, hi);
}
}