我对排序算法有疑问。我正是使用此TimSort来对https://www.geeksforgeeks.org/timsort/(Java)进行排序。例如,我正在读取前2500行的循环内的CSV文件。

这是我的阅读代码:

    private void readFile(){
        try{
            int i = 0;
            BufferedReader csvReader = new BufferedReader(new FileReader(this.filename));
            while ((row = csvReader.readLine()) != null){
                String[] entry = row.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
                if(i > 0 && i <= 2500){
                    int price = Integer.parseInt(entry[5]);
                    entries.add(price);
                }
                i++;
            }
            csvReader.close();

        }catch(Exception e){
            e.printStackTrace();
        }
    }


之后,我以这种方式将字符串转换为int [] Arraylist:

public int[] convertArrayList(){
    ArrayList<Integer> arrayList = this.entries;
    int[] converted = new int[arrayList.size()];
    for(int i=1; i < converted.length; i++){
        converted[i] = arrayList.get(i);
    }
    return converted;
}


我主要有:

    private static synchronized void getPrices(){
        try{
            File dataset = new File("src/CSV/Schools.csv");
            CSVReader reader = new CSVReader(dataset.getCanonicalPath());
            prices = reader.convertArrayList();
        } catch(Exception e){
            e.printStackTrace();
        }
    }


并运行它:

    getPrices();
    int n = prices.length;
    System.out.println(n);

    Instant start = Instant.now();
    System.out.print("Given Array is\n");
    GFG.printArray(prices, n);
    Instant end = Instant.now();

    System.out.println("Time for executing the unsorted array: " + Duration.between(start, end).toNanos());


    GFG.timSort(prices, n);

    Instant start2 = Instant.now();
    System.out.print("\nAfter Sorting Array is\n");
    GFG.printArray(prices, n);
    Instant end2 = Instant.now();

    System.out.println("Time for executing the sorted array: " + Duration.between(start2, end2).toNanos());


现在这是东西
如果我通过将循环更改为i> 0 && i
Exception in thread "main" java.lang.NegativeArraySizeException: -28
at GFG.merge(TimSort.java:32)
at GFG.timSort(TimSort.java:111)
at Main.main(Main.java:27)


它引用了TimSort算法中的merge方法...请问我无法解决这个问题吗?

最佳答案

可能是因为您链接到的TimSort算法实现存在错误。

List.sortCollections.sortArrays.sort(T[])都已使用timsort。无需从随机站点复制代码即可使用TimSort。实用程序方法java.util.Arrays.sort(int[])使用双重透视排序。我认为这具有更好的性能特征,因此代替了timsort。

如果您想了解链接到的timsort代码,请忘记粘贴的所有代码,着重于链接到的timsort隐式代码并进行调试。

09-05 21:40