我正在編寫一個程序,測試一個排序函數是否正確排序程序。我必須讓它測試快速排序和合並排序方法。它也必須詢問用戶想要測試哪種方法並製作一組隨機對象。爲什麼我的程序不能正常運行?它只是爲了快速排序而吐出相同的數組,並且它隨機地重新排列它們以進行合併排序。問題是我的排序方法還是我的測試方法?有人請幫忙。測試排序數組方法
import java.util.Random;
import java.util.Scanner;
public class sortArrays {
public static void main (String[] args)
{
Random gen = new Random();
int[] a = new int[20];
Scanner reader = new Scanner(System.in);
String choice;
int left = a[0];
int right = a[19];
int[] buffer = new int [a.length];
for (int i = 0; i < a.length; i++)
a[i] = gen.nextInt(100);
printArray(a);
System.out.println("Type quick to test the quick sort method.");
System.out.println("Type merge to test the merge sort method.");
choice = reader.nextLine();
if (choice.equals("quick"))
quickSort(a, left, right);
else if (choice.equals("merge"))
mergeSort(a, buffer, 0, 9, 19);
printArray(a);
}
private static void printArray(int[] a)
{
for(int i : a)
System.out.print(i + " ");
System.out.println("");
}
private static void quickSort (int[] a, int left, int right)
{
if (left >= right) return;
int i = left;
int j = right;
int pivotValue = a[(left + right)/2];
while (i < j)
{
while (a[i] < pivotValue) i++;
while (pivotValue < a[j]) j--;
if (i <= j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
quickSort(a, left, j);
quickSort(a, i, right);
}
private static void mergeSort(int[] a, int[] copyBuffer, int low, int middle, int high)
{
int i1 = low, i2 = middle + 1;
for(int i = low; i <= high; i++)
{
if(i1 > middle)
copyBuffer [i] = a[i2++];
else if(i2 > high)
copyBuffer[i] = a[i1++];
else if(a[i1] < a[i2])
copyBuffer[i] = a[i1++];
else
copyBuffer[i] = a[i2++];
}
for(int i = low; i <= high; i++)
a[i] = copyBuffer[i];
}
}
只是爲了簡單的錯誤檢查,添加一個'else System.err.println(「未知選擇:」+選擇);'這將有助於快速確定是否實際調用'quickSort'或'mergeSort'。 –
謝謝,我補充說,但這似乎不成問題。不過謝謝,反正我應該有這個! – user3266115
看來你的排序算法必須正確實現。也許。 – Leo