Each answer that answers this question tells you that O(1) means constant time (no matter what happens with the measurement, there may be a runtime, the number of operations, etc.). This is not true.
To say that the runtime is O(1) means that there is a constant c , so that the runtime is limited above c , regardless of the input. For example, returning the first element of an array of n integers is O(1) :
int firstElement(int *a, int n) { return a[0]; }
But this function is also O(1) :
int identity(int i) { if(i == 0) { sleep(60 * 60 * 24 * 365); } return i; }
The lead time here is limited to 1 year, but in most cases, the lead time is of the order of nanoseconds.
To say that the runtime is O(n) means that there is a constant c , so the runtime is limited above c * n , where n measures the size of the input. For example, searching for the number of occurrences of a certain integer in an unsorted array of integers n using the following algorithm: O(n) :
int count(int *a, int n, int item) { int c = 0; for(int i = 0; i < n; i++) { if(a[i] == item) c++; } return c; }
This is because we have to go through the array, checking each element one at a time.
jason Jan 08 '10 at 19:19 2010-01-08 19:19
source share