嗨,我的代码遇到麻烦了。我的程序应该使用Merge Sort对用户输入的值进行排序。这是我的代码。
public class mergeSort {
private int[] inputArray;
private int[] tempMergeArray;
private int length;
public static void main (String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of your array");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter numbers: ");
for (int i=0; i<array.length; i++){
array[i] = scanner.nextInt();
mergeSort mms = new mergeSort();
mms.sort(array[i]);
for (int j:array){
System.out.println(j);
System.out.print(" ");
}
}
}
public void sort(int array[]){
this.inputArray = array;
this.length = array.length;
this.tempMergeArray = new int [length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex) {
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergeArray[i] = inputArray[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (tempMergeArray[i] <= tempMergeArray[j]) {
inputArray[k] = tempMergeArray[i];
i++;
} else {
inputArray[k] = tempMergeArray[j];
j++;
}
k++;
}
while (i <= middle) {
inputArray[k] = tempMergeArray[i];
k++;
i++;
}
}
第23行有错误:mms.sort(array [i]); 其中说mergeSort类型中的方法sort(int [])不适用于参数(int)。
提前谢谢!
答案 0 :(得分:2)
您的方法传递一个传递单个输入的数组
for (int i=0; i<array.length; i++){
array[i] = scanner.nextInt();
}
mergeSort mms = new mergeSort();
mms.sort(array);
答案 1 :(得分:1)
该方法期待一个数组。您传递的是单个值array[i]
。您需要将其更改为mms.sort(array)
,因为那样您将传入整个数组而不是for循环中位置[i]
的值。