1)
x = 25; for (int i = 0; i < myArray.length; i++) { if (myArray[i] == x) System.out.println("found!"); }
I think this is O (n).
2)
for (int r = 0; r < 10000; r++) for (int c = 0; c < 10000; c++) if (c % r == 0) System.out.println("blah!");
I think this is O (1), because for any input n it will work 10,000 * 10,000 times. Not sure if this is correct.
3)
a = 0 for (int i = 0; i < k; i++) { for (int j = 0; j < i; j++) a++; }
I think this is O (i * k). I really don’t know how to approach such problems, where the inner loop depends on the fact that the variables increase in the outer loop. Some key ideas here will be greatly appreciated. The outer loop runs k times, and the inner loop runs 1 + 2 + 3 + ... + k times. So the sum should be (k / 2) * (k + 1), which would be the order of k ^ 2. So will it really be O (k ^ 3)? It seems too big. Again, I do not know how to approach this.
4)
int key = 0; //key may be any value int first = 0; int last = intArray.length-1;; int mid = 0; boolean found = false; while( (!found) && (first <= last) ) { mid = (first + last) / 2; if(key == intArray[mid]) found = true; if(key < intArray[mid]) last = mid - 1; if(key > intArray[mid]) first = mid + 1; }
This, I think, is O (log n). But I came to this conclusion, because I believe that this is a binary search, and I know from reading that the runtime is O (log n). I think this is because you divide the input size by 2 for each iteration of the loop. But I don’t know if this is the correct argument or how to approach similar algorithms that I have not seen and be able to deduce that they work in logarithmic time in a more verifiable or formal way.
5)
int currentMinIndex = 0; for (int front = 0; front < intArray.length; front++) { currentMinIndex = front; for (int i = front; i < intArray.length; i++) { if (intArray[i] < intArray[currentMinIndex]) { currentMinIndex = i; } } int tmp = intArray[front]; intArray[front] = intArray[currentMinIndex]; intArray[currentMinIndex] = tmp; }
I am confused by this. The outer loop runs n times. And the inner loop of the cycle n + (n-1) + (n-2) + ... (n - k) + 1 times? That is, O (n ^ 3)?
source share