我正在尝试获取快速排序算法对从文本文件加载的ArrayList
进行排序所需的平均时间。我想在for
循环中运行我的代码10次。我的问题是代码在第一次运行后运行得更快。
下面的代码
public static void main(String args[]) throws FileNotFoundException {
Timer timer = new Timer();
Scanner input = new Scanner(new File(".\\Seminar 1 - File with random numbers.txt"));
ArrayList<Integer> arr = new ArrayList<>();
System.out.println("Number of array elements recursive quick sort, median of 3 pivot");
System.out.println("1-1000000");
Scanner sizeInput = new Scanner(System.in);
int numElements = sizeInput.nextInt();
for (int counter = 0; counter < 10; counter++) {
while (input.hasNextLine() && arr.size() < numElements) {
arr.add(input.nextInt());
}
// Function calling
timer.startTimer();
qSort(arr, 0, arr.size() - 1);
timer.stopTimer();
// for (int i = 0; i < arr.size(); i += 1) {
// System.out.println(arr.get(i));
// }
System.out.println(timer.getTime());
}
}
是否有一种方法可以重置内存或导致此的原因?
由于for循环中的后续迭代,因此几乎几乎为零。如何:
第一次之后:
该文件已被读取。没有数据可再次读取,并且数组已经初始化和排序。因此,从您的示例代码来看,这是预期的行为。
如果您确实要重新运行整个程序,请尝试将文件初始化的for循环移出:
...
...
for (int counter = 0; counter < 10; counter++) {
Scanner input = new Scanner(new File(".\\Seminar 1 - File with random numbers.txt"));
ArrayList<Integer> arr = new ArrayList<>();
System.out.println("Number of array elements recursive quick sort, median of 3 pivot");
System.out.println("1-1000000");
Scanner sizeInput = new Scanner(System.in);
int numElements = sizeInput.nextInt();
while (input.hasNextLine() && arr.size() < numElements) {
arr.add(input.nextInt());
}
// Function calling
timer.startTimer();
qSort(arr, 0, arr.size() - 1);
timer.stopTimer();
// for (int i = 0; i < arr.size(); i += 1) {
// System.out.println(arr.get(i));
// }
System.out.println(timer.getTime());
....
您还可以重新初始化/制作原始数组的副本并使用该数组运行快速排序。