# What is the Big-Oh Runtime (in terms of n) for the following segment of code? int i;int used[n];for (i = 0; i < n; i++) {    used[i] = 0;}for (i = 0; i < n; i++) {    if (used[i] == 0) {        used[i] = 1;        i = -1;     }}

Question
12 views

What is the Big-Oh Runtime (in terms of n) for the following segment of code?

int i;

int used[n];

for (i = 0; i < n; i++) {

used[i] = 0;

}

for (i = 0; i < n; i++) {

if (used[i] == 0) {

used[i] = 1;

i = -1;

}

}

check_circle

Step 1

Generally, we define the complexity of any code by using Big O- Notation. The complexity depends upon the kind of statements used in the code.

1)Sequence of statements-

statement 1;

statement 2;

...

statement k;

The total time is determined by adding the times for all statements:

total time = time(statement 1) + time(statement 2) + ... + time(statement k)

If each statement  involves basic operations, then the time for each statement is constant and the total time is also constant: O(1).

2) if-then-else statements

if (condition) {

sequence of statements 1

}

else {

sequence of statements 2

}

In this case, either sequence 1 will execute, or sequence 2 will execute. Therefore, the worst-case time is the slowest of the two possibilities: max(time(sequence 1), time(sequence 2)). For example, if sequence 1 is O(N) and sequence 2 is O(1) the worst-case time for the whole if-then-else statement would be O(N).

3) for loops

for (i = 0; i < N; i++) {

&nb...

### Want to see the full answer?

See Solution

#### Want to see this answer and more?

Solutions are written by subject experts who are available 24/7. Questions are typically answered within 1 hour.*

See Solution
*Response times may vary by subject and question.
Tagged in

### Computer Science 