这是我在java中实现Merge Sort
import java.io.*;
import java.util.Arrays;
public class MergeSort
{
private static int [] LeftSubArray(int [] Array)
{
int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
return leftHalf;
}
private static int [] RightSubArray(int [] Array)
{
int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length);
return rightHalf;
}
private static int [] Sort(int [] A)
{
if(A.length > 1)
{
return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
}
else
{
return A;
}
}
private static int [] Merge(int [] B, int [] C)
{
int [] D = new int[B.length + C.length];
int i,j,k;
i = j = k = 0;
while(k < D.length)
{
if(i == B.length)
{
//Copy the remainder of C into D
while(k < D.length){ D[k++] = C[j++]; }
}
if(j == C.length)
{
//Copy the remainder of B into D
while(k < D.length){ D[k++] = B[i++]; }
}
if(i<B.length && j<C.length)
{
if(B[i] > C[j]){ D[k++] = B[i++]; }
else { D[k++] = C[j++]; }
}
}
return D;
}
public static void main(String [] args)
{
int [] array = {1,3,5,2,4};
int [] sorted = MergeSort.Sort(array);
for(int i = 0;i < sorted.length; ++i)
{
System.out.print(sorted[i] + " ");
}
}
}
我得到的输出是
2 1
据我所知,我对右子阵列的划分似乎存在问题。 我做错了什么?
答案 0 :(得分:2)
如果你的数组有10个元素,那么LeftSubArray复制元素0..5,RightSubArray复制元素6..10。但是如果第一个元素在索引0处,则没有元素w /索引10.并且如果copyOfRange(a,b)给出索引a..b-1的元素,则LeftSA产生0..4并且RightSA是屈服6..9。无论哪种方式,你对分裂的假设似乎都是准确的。
答案 1 :(得分:2)
这是copyOfRange的javadoc:
Parameters:
original - the array from which a range is to be copied
from - the initial index of the range to be copied, **inclusive**
to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.)
我强调了你应该特别注意的两个词; - )
答案 2 :(得分:1)
您的代码[1,3,5,2,4]分为[1,3]和[2,4]。祝你好运
答案 3 :(得分:1)
这段代码有效:你有几个错误: 看下一个差异:
有效的代码如下:
public class MergeSort
{
private static int [] LeftSubArray(int [] Array)
{
int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
return leftHalf;
}
private static int [] RightSubArray(int [] Array)
{
int[] rightHalf = Arrays.copyOfRange(Array, Array.length / 2,
Array.length);
return rightHalf;
}
private static int [] Sort(int [] A)
{
if(A.length > 1)
{
return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
}
else
{
return A;
}
}
private static int [] Merge(int [] B, int [] C)
{
int [] D = new int[B.length + C.length];
int i,j,k;
i = j = k = 0;
while(k < D.length)
{
if(i == B.length)
{
//Copy the remainder of C into D
while (j < C.length) {
D[k++] = C[j++];
}
}
if(j == C.length)
{
//Copy the remainder of B into D
while (i < B.length) {
D[k++] = B[i++];
}
}
if (i < B.length && j < C.length)
{
if (B[i] > C[j]) {
D[k++] = B[i++];
} else {
D[k++] = C[j++];
}
}
}
return D;
}
public static void main(String [] args)
{
int [] array = {1,3,5,2,4};
int [] sorted = MergeSort.Sort(array);
for(int i = 0;i < sorted.length; ++i)
{
System.out.print(sorted[i] + " ");
}
}
}
答案 4 :(得分:1)
我在Robert Sedgewick的书“Java语言算法”
中找到了正确的解决方案