When I determine the complexity of a Java code like this , do I have to express that in a Theta or a big O notation?
List<Person> sortedPersons = new ArrayList<Person>();
List<Person> people = new ArrayList<Person>();
for (int i = 0; i < people.size(); i++) {
Person toadd = people.get(i);
int index = 0;
while(index < sortedPersons.size() && sortedPersons.get(index).compareTo(toadd) < 0)
index++;
sortedPersons.add(index, toadd);
}
I know the for-loop is O(n) (or is it \Theta(n)?) A get-operation runs in constant time, so O(1). But what about the while loop? sortedPersons.size(): O(1) sortedPersons.get(): O(1) Is the compareTo-operation linear? And I think the add-operation also runs in constant time. What's the total complexity of the code?
the code is O(n²) If you consider numbers and you sort them from small to large.
The code is just a variant of Insertion sort, it just uses a list instead of an array.
Consider this example for the complexity:
The numbers are 1 2 3 4 5 and you want to sort from small to big.
In the end you will have something like: 0 1 2 3 4 time's visited the inner loop.
Now you can write 1 2 3 4 5 as (5(5+1))/2).
Now you can write O(n(n+1) / 2 + n) as O(n²).