'What is the most efficient way to add edges to a graph from permutation of numbers?

If I have an array of numbers such as: {3,2,4,6,1,5,9}

What is the best way to construct a graph such that for each index i and k, i < k and their respective values p_i > p_k?

For example, an edge should be created for the following situations: 3--2 3--1

since 3 is at index 0 and 2 is at index 1, i < k. But 3 > 2. p_i > p_k.

From 6, There should be an edge from 6<-->1 and 6<-->5 since the index where 6 is at is less than the indexes where 1 and 5 are but the value of the 3rd index(6) is greater than the values at the 4th(1) and 5th(5) indexes.

The complete graph should have the following edges:

3--2

3--1

2--1

4--1

6-1

6-5

This is what I have:

for (int i = 0; i < numbers.length; i++) {
    for (int j = i + 1; j < numbers.length; j++) {
        if (numbers[i] > numbers[j]) {
            graph.addEdge(numbers[i], numbers[j]);
            graph.addEdge(numbers[j], numbers[i]);
                    }
                }
            }

However, the array in question has over 60 thousand numbers and the O(n^2) complexity takes way too long...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source