以下是我对合并排序的实现。
private static void mergeSort(int[] a, int low , int high,int[] res)
{
int mid = (low + high) /2;
if (low < high)
{
mergeSort(a,low,mid-1,res);
mergeSort(a,mid,high-1,res);
merge(a,low,mid,high,res);
}
}
private static void merge(int[] a, int low , int mid , int high,int[] res)
{
int i = low;
int j = mid ;
int k =0;
while (i < mid && j < high)
if(a[i] < a[j])
res[k++] = a[i++];
else
res[k++] = a[j++];
while(i < mid)
res[k++] = a[i++];
while(j < high)
res[k++] =a[j++];
}
当我在main方法中运行此程序时,我打印出原始数组。不确定是什么问题。当我单独测试时,合并方法有效。
public static void main(String[] args)
{
int[] a = {45,24,53,13,54,45,63,23};
int[] res = new int[a.length];
mergeSort(a,0,a.length,res);
for(int i=0 ; i < res.length ; i++)
{
System.out.print(res[i] +",");
}
}
输出
45,24,53,13,54,45,63,23,
我花了很多时间寻找问题。我无法修复它。
答案 0 :(得分:1)
问题实际上相当复杂。
主要问题是您只是合并到res
,但您再也不会使用它了。所以你最终会用每个递归级别覆盖它。
以下是在a
和res
之间来回合并的修补版本。它确实会破坏a
的内容,所以它可能不是你想要的。
private static void mergeSort(int[] a, int low , int high,int[] res)
{
int mid = (low + high) /2;
if (low + 1 < high)
{
// Sort sub-parts
mergeSort(a,low,mid,res);
mergeSort(a,mid,high,res);
// Copy back to "a"
for (int c = low; c < high; c++){
a[c] = res[c];
}
// Merge back to "res"
merge(a,low,mid,high,res);
}else{
res[low] = a[low];
}
}
private static void merge(int[] a, int low , int mid , int high,int[] res)
{
int i = low;
int j = mid;
int k = low; // Use "low" instead of 0.
while (i < mid && j < high)
if(a[i] < a[j])
res[k++] = a[i++];
else
res[k++] = a[j++];
while(i < mid)
res[k++] = a[i++];
while(j < high)
res[k++] =a[j++];
}
输出:
13,23,24,45,45,53,54,63,
答案 1 :(得分:1)
答案是@Mysticial sais,除了需要在merge方法中复制数组:
private static void mergeSort(int[] a, int low , int high,int[] res)
{
int mid = (low + high) /2;
if (low + 1 < high)
{
// Sort sub-parts
mergeSort(a,low,mid,res);
mergeSort(a,mid,high,res);
// Merge back to "res"
merge(a,low,mid,high,res);
}else{
res[low] = a[low];
}
}
private static void merge(int[] a, int low , int mid , int high,int[] res)
{
int i = low;
int j = mid;
int k = low; // Use "low" instead of 0.
while (i < mid && j < high)
if(a[i] < a[j])
res[k++] = a[i++];
else
res[k++] = a[j++];
while(i < mid)
res[k++] = a[i++];
while(j < high)
res[k++] =a[j++];
// Copy back to "a"
for (int c = low; c < high; c++){
a[c] = res[c];
}
}
无论如何,请注意这样做会覆盖原始数组......因此您可能希望将调用包装为mergeSort以避免它:
private static int[] mergeSort(int[] a){
int[] b = new int[a.length];
int[] tmp = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length);
mergeSort(b, 0, b.length, tmp);
return b;
}
public static void main(String[] args) {
int[] a = {45, 24, 53, 13, 54, 45, 63, 23};
int[] res = mergeSort(a);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + ",");
}
}
希望这有帮助!