我一直在尝试优化这个mergesort版本,但是需要很长时间来排序大约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++;
}
}}
答案 0 :(得分:4)
你永远不会清除helper
的内容(不应该是全局的),这意味着每次合并越来越多的数据。我真的很惊讶你没有失去记忆。
答案 1 :(得分:0)
您的代码是否正在运行且o / p是alryt? 在合并函数中,在第一个while循环之后必须有另一个循环。第一个while循环终止,因为j>高或i>中。你刚刚写了j&gt;高条件,dere is no i&gt;中间condtn。之后那个循环必须是像dis这样的东西
if(j>high)
{
while (i <= middle) {
numbers.set(k,helper.get(i));
k++;
i++;
}
}
else
{
while (j <= high) {
numbers.set(k,helper.get(j));
k++;
j++;
}
}
N清除助手