我尝试使用下面的代码在Java中实现合并排序。 UnhandledException
方法应该是一种递归方法,它可以将数组重复地分成较小的部分,而mergeSort()
方法则采用已经被排序的数组的2个部分,并将它们合并为一个已排序的部分
这是代码:
merge()
然后,主类生成一个具有用户定义长度的数组,并使用随机整数填充该数组,然后将其传递给class MergeSort{
public static void mergeSort(int[] array){
mergeSort(array, 0, array.length-1);
}
public static void mergeSort(int[] array, int start, int end){
int mid = (start + end)/2;
if (end > start) {
mergeSort(array, start, mid);
mergeSort(array, mid + 1, end);
merge(array, start, end, mid + 1);
}
}
public static void merge(int[] array, int start, int end, int mid){
int length = end - start + 1,length1 = mid- start, length2 = end - mid + 1, index1 = start, index2 = mid, sortedindex = 0;
boolean cont = true;
int[] sortedArray = new int[length];
while (cont){
if (array[index1] > array[index2]){
sortedArray[sortedindex] = array[index2];
index2++;
} else{
sortedArray[sortedindex] = array[index1];
index1++;
}
sortedindex++;
//reached the end of one array, dump the rest of the remaining array in the sorted array
if (index1 >= length1){
for (index2 = index2; index2 < length2; index2++){
sortedArray[sortedindex] = array[index2];
sortedindex++;
}
cont = false;
} else if (index2 >= length2){
for (index1 =index1; index1 < length1; index1++){
sortedArray[sortedindex] = array[index1];
sortedindex++;
}
cont = false;
}
}
//copy the sorted array into the main array
for (int i = 0; i <= length - 1; i++){
array[start+i] = sortedArray[i];
}
}
}
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
Random random = new Random();
int length = scanner.nextInt();
int[] array = new int[length];
for (int i = 0; i < length;i++){
array[i] = random.nextInt(5000);
//System.out.println(array[i]);
}
MergeSort.mergeSort(array);
for (int i: array){
System.out.println(i);
}
}
}
。
不幸的是,程序输出了一个数组,其中前几个元素已正确排序,而其余元素为零。例如给定一个随机生成的数组mergeSort()
,程序将输出{3291, 2879, 3078, 3609, 3534, 3922, 2793, 1098, 472, 1800}
,并且输出中正确排序的元素数量因运行而异。
我似乎无法弄清楚我的代码出了什么问题。任何帮助将不胜感激:)
答案 0 :(得分:0)
while循环应更早关闭。
public static void merge1(int[] array, int start, int end, int mid) {
int length = end - start + 1;
int[] sortedArray = new int[length];
int index1 = start;
int index2 = mid + 1;
int sortedindex = 0;
while (index1 <= mid && index2 <= end) {
if (array[index1] < array[index2]) {
sortedArray[sortedindex++] = array[index1++];
} else {
sortedArray[sortedindex++] = array[index2++];
}
}
// reached the end of one array, dump the rest of the remaining array in the
// sorted array
while (index1 <= mid) {
sortedArray[sortedindex++] = array[index1++];
}
while (index2 <= end) {
sortedArray[sortedindex++] = array[index2++];
}
// copy the sorted array into the main array
for (int i = 0; i <= length - 1; i++) {
array[start + i] = sortedArray[i];
}
}