我是一个新的编程和工作的程序,存储在两个数组的执行时间,timeInsertionSort和timeQuickSort,然后写入一个CSV文件名为“execution_times.csv”。我运行我的程序,它永远不会停止。该程序应该去L = 200,000和停止。需要帮助,不知道如何修复。如果你可以提供代码,代码中的什么需要修复
线程“main”中出现异常java.lang.StackOverflowError
import java.util.Random;
import java.io.PrintWriter;
import java.io.IOException;
public class SortingAlgorithms {
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int j = 1; j < n; j++) {
int key = arr[j];
int i = j - 1;
while (i >= 0 && arr[i] > key) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = key;
}
}
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int pivotIndex = partition(arr, left, right);
quickSort(arr, left, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, right);
}
}
private static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, right);
return i + 1;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
Random rand = new Random();
int L = 200000;
int[] arr = new int[L];
long[] timeInsertionSort = new long[L];
long[] timeQuickSort = new long[L];
for (int n = 1; n <= L; n++) {
for (int i = 0; i < n; i++) {
arr[i] = rand.nextInt(n);
}
long start = System.nanoTime();
insertionSort(arr);
long end = System.nanoTime();
timeInsertionSort[n-1] = end - start;
start = System.nanoTime();
quickSort(arr, 0, n - 1);
end = System.nanoTime();
timeQuickSort[n-1] = end - start;
}
// Write the execution times to a CSV file
try {
PrintWriter writer = new PrintWriter("execution_times.csv", "UTF-8");
writer.println("n,TInsertionSort(n),TQuickSort(n)");
for (int n = 1; n <= L; n++) {
writer.println(n + "," + timeInsertionSort[n-1] + "," + timeQuickSort[n-1]);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
数据转到csv文件
1条答案
按热度按时间ntjbwcob1#
你的测试很不公平:
给
quickSort
一个已经排序的数组,并强制它进入最坏的情况。200000个堆栈帧足以溢出堆栈。为了公平起见,制作数组的副本,并对副本进行独立排序。