For the following code how many comparison operations occur

For the following code, how many comparison operations occur? Comparisons are operations like ==, !=, <, <=, >, and >=. Assignments like ++ and = are NOT comparisons.

for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
    if (arr[j] < arr[i]) {
      temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
}
}

Solution

for (int i = 0; i < 100; i++)

for this loop comparison will happen till i value reaches 100

So, from 0 to 100 there 101 comparisons in total

for (int j = 0; j < 100; j++)

for this loop comparison will happen till j value reaches 100

So, from 0 to 100 there 101 comparisons in total

Since the second loop will run 100 times there for there will be

101*100 = 10100 comparisons for second loop.

if (arr[j] < arr[i])

This condition will run for 100 times in second loop and second loop runs for 100 times there fore total comparisons for this line is

100*100 = 10000

hence the total comparisons are

10000+10100+101 = 20201 comparisons in total

For the following code, how many comparison operations occur? Comparisons are operations like ==, !=, <, <=, >, and >=. Assignments like ++ and = ar

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site