java - 为什么合并排序需要花费太多时间来排序?

标签 java sorting

我一直在尝试优化这个合并排序版本,但是对大约 300 万个寄存器进行排序需要太长时间。我哪里做错了?我希望得到一些帮助,谢谢。

Persona 是一个包含字符串和整数的类,以防万一你们想知道以帮助我。

public class Mergesort {
  private ArrayList<Persona> numbers = new ArrayList();
  private  ArrayList<Persona> helper;
  private int number;
  private boolean ascending;


  public void sort(ArrayList<Persona> values, boolean ascending) {
    this.numbers = values;
    this.ascending = ascending;
    number = values.size();
    helper = new ArrayList();
    mergesort(0, number - 1);
  }

  /**
   * Determines the middle of the array to sort the left side and the right side 
   * Then it merges both arrays.
   * @param low
   * @param high 
   */
  private void mergesort(int low, int high) {
    // check if low is smaller then high, if not then the array is sorted
    if (low < high) {
      // Get the index of the element which is in the middle
      int middle = low + (high - low) / 2;
      // Sort the left side of the array
      mergesort(low, middle);
      // Sort the right side of the array
      mergesort(middle + 1, high);
      // Combine them both
      merge(low, middle, high);
    }
  }

  /**
   * Merges the arrays.
   * @param low
   * @param middle
   * @param high 
   */
  private void merge(int low, int middle, int high) {

    // Copy both parts into the helper array
    for (int i = low; i <= high; i++) {
          helper.add(i, numbers.get(i));
    }

    int i = low;
    int j = middle + 1;
    int k = low;
    // Copy the smallest values from either the left or the right side back
    // to the original array
    while (i <= middle && j <= high) {
      if ( helper.get(i).id  <= helper.get(j).id) {
        numbers.set(k, helper.get(i));
        i++;
      } else {
        numbers.set(k,helper.get(j));
        j++;
      }
      k++;
    }
    // Copy the rest of the left side of the array into the target array
    while (i <= middle) {
      numbers.set(k,helper.get(i));
      k++;
      i++;
    }
  }}

最佳答案

你永远不会清除helper的内容(无论如何它不应该是全局的),这意味着每次你合并越来越多的数据。我真的很惊讶你没有内存不足。

关于java - 为什么合并排序需要花费太多时间来排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837961/

相关文章:

java - 将所有图像转换为 PNG

javascript - UnderscoreJS 对象组列表

java - 快速排序和中值实现的堆栈溢出错误

java - LisrView 子项的不同颜色

java - 在 Java 中,运算符对原始类型和原始包装类的执行是否相同?

java - 如何从 ArrayList<ArrayList<String>>.get() 返回 ArrayList<String>

java - 这是合并排序吗?

java - 从 rpm 运行类文件

Python Pandas 按二级索引(或任何其他级别)切片多索引

python - Pandas:如何在 python3 中对混合类型的多索引使用切片?