为什么我的mergesort比我的quicksort慢?
他们都是同样的时间复杂性,但是当我在具有100,000个条目的随机生成链表上运行合并排序时:
public LinkedList<Integer> linkedListSort(LinkedList<Integer> list) {
if (list.size() <= 1) return list;
LinkedList<Integer> left = new LinkedList<Integer>();
LinkedList<Integer> right = new LinkedList<Integer>();
int middle = list.size()/2;
for (int i = 0; i < middle; i++) {
left.add((int)list.get(i)); steps++;
}
for (int i = middle; i < list.size(); i++) {
right.add((int)list.get(i)); steps++;
}
left = linkedListSort(left);
right = linkedListSort(right);
return merge(left, right);
}
public LinkedList<Integer> merge(LinkedList<Integer> left, LinkedList<Integer> right) {
LinkedList<Integer> result = new LinkedList<Integer>();
while (!(left.isEmpty()) && !(right.isEmpty())) {
steps++;
if ((int)left.peekFirst() <= (int)right.peekFirst()) {
result.add(left.poll());
} else {
result.add(right.poll());
}
}
while (!(left.isEmpty())) {result.add(left.poll()); steps++;}
while (!(right.isEmpty())) {result.add(right.poll()); steps++;}
return result;
}
这比我的快速排序慢很多,它是:
public String arraySort(int[] array, int startIndex, int endIndex, int steps) {
int leftIndex = startIndex;
int rightIndex = endIndex;
int pivot = array[(leftIndex + rightIndex) / 2];
while (leftIndex <= rightIndex) {
steps++;
//search for an element with a higher value than the pivot, lower than it
while (array[leftIndex] < pivot) {steps++; leftIndex++;}
//search for an element with a lower value than the pivot, higher than it
while (array[rightIndex] > pivot) {steps++; rightIndex--;}
//check the left index hasn't overtaken the right index
if (leftIndex <= rightIndex) {
//swap the elements
int holder = array[leftIndex];
array[leftIndex] = array[rightIndex];
array[rightIndex] = holder;
leftIndex++; rightIndex--;
}
}
if (leftIndex < endIndex) arraySort(array, leftIndex, endIndex, steps);
if (rightIndex > startIndex) arraySort(array, startIndex, rightIndex, steps);
return "Quicksort on an unsorted array took " + steps + " steps.";
}
这是什么原因? 我的quicksort / mergesort不是它应该是的还是mergesort在链接列表上执行的数量很大的随机数? 或者是其他东西?
谢谢!
你已经实现了一个快速排序的版本,它可以“就地”做所有事情,而你的mergesort在每次递归调用时都会复制左/右的内容(以及与merge()
同样的事情)。 这可能是造成差异的主要原因。
其次,就像上面评论中提到的Luiggi--你如何做你的基准测试? 你有没有得到适当的JVM热身? 你是否运行足够的周期并取平均值? 对JVM进行适当的基准测试可能会很棘手:如果您没有经验,最好找一个微型基准测试框架并使用它!
链接地址: http://www.djcxy.com/p/31583.html