I've created a very simple linked list in 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++;
}
}
So in the main class, I'll be adding elements to the linked list in a random order. But how can I create a method that counts the number of inversions in the linked-list?
So far, I've managed to achieve it with O(N^2) running time:
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;
}
However, as I said, the running time for this algorithm is O(N^2). I'm trying to achieve a running time of O(NlogN). How can this be achieved?