我创建了一个MergeSort算法来输出随机分类的数字。但是我遇到了一些问题:
1。)我不明白为什么我的“After”结果会返回不同的结果数字和/或多个相同的数字ex:
Before sorting:
66 71 45 79 69 95 95 93 83 28
After sorting:
28 28 83 93 95 95 83 93 95 95
我的代码中是否遗漏了一个简单的错误?
2。)此外,我如何显示此算法正在执行的交换次数。
非常感谢任何建议,改进和/或见解!
以下是我正在使用的代码:
public class MergeSort
{
public static void main (String [] args)
{
int A [] = new int [10];
populateA(A);
System.out.println("Before sorting: ");
printA(A);
A = merge_sort(A);
System.out.println("\nAfter sorting: ");
printA(A);
}
public static int []merge_sort(int [] B)
{
if(B.length <= 1)
{
return B;
}
int midpoint = B.length/2;
int[] left = new int[midpoint];
int[] right;
if(B.length %2 == 0)
{
right = new int[midpoint];
}
else
{
right = new int[midpoint+1];
}
int [] result = new int [B.length];
for (int i = 0 ; i < midpoint; i++)
{
left[i] = B[i];
}
int x=0;
for (int j = midpoint; j < B.length; j++)
{
if(x < right.length)
{
right[x] = B[j];
x++;
}
}
left = merge_sort(left); // merge results into left
right = merge_sort(right); //merge results into right
result = merge(left, right); // combine both results in merge
return result; // return result
}
public static int []merge(int [] left, int [] right)
{
int lengthResult = left.length + right.length;
int [] result = new int [lengthResult];
int indexL = 0;
int indexR = 0;
int indexRes = 0;
while(indexL < left.length || indexR < right.length)
{
if(indexL < left.length && indexR < right.length)
{
if (left[indexL] <= right[indexR])
{
result [indexRes] = right[indexL];
indexL++;
indexRes++;
}
else
{
result [indexRes] = right[indexR];
indexR++;
indexRes++;
}
}
else if (indexL < left.length)
{
result [indexRes] = left[indexL];
indexL++;
indexRes++;
}
else if (indexR < right.length)
{
result [indexRes] = right[indexR];
indexR++;
indexRes++;
}
}
return result;
}
public static void printA (int [] B)
{
for(int i=0; i < B.length; i++)
{
System.out.print(B[i]+" ");
}
}
public static int[] populateA(int [] B)
{
for(int i=0; i < B.length; i++)
{
B[i] = (int)(Math.random()*100); // Generate random numbers to fill array size
}
return B;
}
}
答案 0 :(得分:0)
left
,right
,mid
的数组。查看this链接。答案 1 :(得分:0)
更仔细地检查此代码段,您有一个拼写错误(访问right
而不是left
):
if (left[indexL] <= right[indexR])
{
result [indexRes] = right[indexL];
indexL++;
indexRes++;
}
else
{
result [indexRes] = right[indexR];
indexR++;
indexRes++;
}
说到交换,合并排序通常不像其他排序算法那样交换元素,但您可以比较indexL
和indexR
以获得类似的度量。有关详细信息,请参阅this question。