【发布时间】:2023-05-06 22:44:01
【问题描述】:
我正在编写一个程序来测试排序函数是否正确地对程序进行排序。我必须让它测试快速排序和合并排序方法。它还必须询问用户他们想要测试哪种方法并制作一个随机对象数组。为什么我的程序不能正常运行?它只是为快速排序吐出相同的数组,然后随机重新排列它们以进行合并排序。问题是我的排序方法还是我的测试方法?有人请帮忙。
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("Unknown choice :" + choice);这将有助于快速识别quickSort或mergeSort是否被实际调用.. -
谢谢,我补充了,但这似乎不是问题。不过谢谢,我可能应该有那个!
-
看来您的排序算法必须正确实现。也许吧。
-
@Leo 快速排序没问题,但他只实现了归并排序的“归并”操作;不是整个算法。
标签: java arrays quicksort mergesort