为什么我的mergesort比我的quicksort慢?

时间:2015-04-18 21:00:05

标签: java sorting time-complexity quicksort mergesort

他们同时具有复杂性,但是当我在一个随机生成的链表上运行我的合并排序时,有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在具有大量随机数的链表上表现不佳?或其他什么?

谢谢!

1 个答案:

答案 0 :(得分:3)

您已经实施了一个快速排序版本,可以随时随地执行所有操作&#34;&#34;您的mergesort在每次递归调用时复制左/右内容(与merge()相同)。这可能是导致分歧的主要原因。

其次,就像上面评论中提到的Luiggi一样 - 你如何进行基准测试?你有适当的JVM热身吗?你运行足够的周期并取平均值吗?使用JVM进行适当的基准测试可能很棘手:如果您没有使用它的经验,最好寻找micro-benchmarking framework并使用它!