r/javahelp • • Jan 04 '19

Solved When is a loop o(1)?

I'm super confused about when a for loop/while loop is o(1).

For instance if I have an array A= {1,2,3,4,5};

for(int i = 0; i< A.length; i++){
//append to string or something
}

This loop would be O(n) ? I understand if I loop: for(int i = 0; i< 100; i++){ //append to string or something }

This is constant time but when else is a loop constant time?

16 Upvotes

8 comments sorted by

View all comments

0

u/philipwhiuk Employed Java Developer Jan 04 '19 edited Jan 04 '19

If it does 1 thing per item, it's O(n).

If you want O(1) it can only do one thing no matter how many items exist.

"Reading the first element" is O(1) in a typical list.

"Reading an element" can either be O(1) for an array or O(n) for a linked list (because in the worst case you have to read each element to find the next all the way to the end of the list). For a heap it's O(n log n).

Something like sorting is not possible in O(n) because you have to do multiple comparisons between members of the list. Hence the best sort is O(n log n).