使用O(n log n)运行时间计算链表中的反转

时间:2017-09-19 10:38:52

标签: java algorithm linked-list time-complexity inversion

我在Java中创建了一个非常简单的链表:

public class LinkedList {
    class Node {
        public Node next;
        public int item;

        public Node (int item) {
            this.item = item;
        }
    }

    int listSize = 0;
    Node first = null;
    Node last = null;

    public void add(int n) {
        Node node = new Node(n);
        if (first == null) {
            first = node;
        } else {
            last.next = node;
        }
        last = node;
        listSize++;
    }
}

所以在主类中,我将以随机顺序向链表添加元素。但是,如何创建一个计算链表中反转次数的方法?

到目前为止,我已经设法用O(N ^ 2)运行时间来实现它:

    public int inversionCount() {
        int count = 0;
        Node current = this.first;
        for (int i = 0; i <= this.listSize - 2; i++) {
            Node next = current.next;
            for (int j = i + 1; j < this.listSize; j++) {
                if (current.item > next.item) {
                    System.out.print("(" + current.item + "," + next.item + ")" + " ");
                    count += 1;
                }
                next = next.next;
            }
            current = current.next;
        }
        return count;
    }

然而,正如我所说,这个算法的运行时间是O(N ^ 2)。我试图实现O(NlogN)的运行时间。如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

您正在使用具有 O(n ^ 2)

复杂度的冒泡排序

对于链表,适用于 O(n log n)复杂度的算法是合并排序

请参阅this walk trough of merge sort for linked lists

答案 1 :(得分:0)

在插入排序中,它会在普通数组上花费 o(n) ,即使您使用二分搜索来查找元素需要排序的位置,它也会花费 o(n) 为数组腾出新空间。在链表中,插入需要 o(1) 并且通过二分查找,您可以获得 o(nlogn) 的复杂度。从那里您可以通过计算要移动的索引减去前一个索引的计算来计算此数组的反转。每次将所有这些计算加起来就可以得到数字反演。