Determining the Big-O of this algorithm

Viewed 194

I'm trying to understand what the Big-O is of the code below.

What the code is supposed to do

Essentially, I am trying to select a subset (max size = selectionSize) of random nodes and any edges that exists between them. The selection of random nodes is done in the while loop. After having done that, I want to select any edges that exist between the selected nodes.

What I think it is & why

I think the running time is O = n^2 where n=selectionSize. The reason is: even though I can increase the size of the elements in nodes (e.g. make it 10000), I don't believe it can affect the algorithm since I am only looping through the maximum of selectionSize. The only reason I am a bit worried that this is wrong is because of the while loop, where I select random elements from the list up until I have enough. While this can take quite long (because it is random), I don't think it affects the overall output in terms of time. Edit: ugh on second thoughts... Nevermind... The nodes size does affect it (since node.getNeighbors()can be at most the size of the nodes).. So I think that if the selectionSize is equal to the size of nodes, the running time is O=n^2 where n=size of nodes.

Any tips/hints would be appreciated.

Code

// nodes and selectionSize are my input:
int[] nodes = {1,2,3...,1000}; // 1000 elements
int selectionSize = 500; // This can be at most the size of the elements (in this case 1000)

run_algo(nodes, selectionSize);

public void run_algo(int[] nodes, int selectionSize) {
    randomNodesList = {};

    while(randomNodesList < selectionSize) {
        randomNode = selectRandomNode(nodes); // Assume O(1)

        if(!randomNodesList.exists(randomNode)) { // Assume O(1)
            randomNodesList.push_back(randomNode); // Assume O(1)
        }
    }

    foreach(node in randomNodesList) {
        foreach(neighbor in node.getNeighbors()) { // Max. nodes size (in this case 1000)
            if (!randomNodesList.exists(neighbor)) { // Assume O(1)
                AddEdge(node, neighbor); // Takes O(1) time
            }
        }
    }
}
2 Answers
Related