for n
= 5, the values of i
and j
encountered when the if
statement is executed can be listed as follows:
(4,0) (4,1) (4,2) (4,3)
(3,0) (3,1) (3,2)
(2,0) (2,1)
(1,0)
I arranged the items like that on purpose because they form a triangle.
####
###
##
#
To count how many items are in this triangle we can mirror the triangle and count each item twice. There are two ways to do it neatly depending on whether you place the mirrored items to the right or below.
####o
###oo
##ooo
#oooo
####
###o
##oo
#ooo
oooo
Either way, by inspecting width times height, this can easily be seen to be a rectangle of either n * (n-1)
or (n-1) * n
items (equal area in both cases). And since we counted each element twice, we can divide by two, and use (n-1) * n / 2
as the formula for the number of items.
Therefore your if
condition will be computed exactly (n-1) * n / 2
times.
You also correctly expanded this expression to be ((n*n) - (n)) / 2
which is also equal to (n^2 - n) / 2
.
But a few things were bad...
You said (i-1)*i/2
, using i
instead of n
. That's not right.
Your code appears to intend to compute a Bubble sort. And the index for the if
condition and its block should be j
(not i
) throughout. (You were comparing arr[i]
to arr[i+1]
for the same value of i
repeatedly in the inner loop. The actual swap would be evaluated at most once for a given value of i
, in that case, or not at all, depending on the values of arr
.)
The code you intended was likely:
for (i = n-1; i>0; i--)
for (j=0; j<i; j++)
if (arr[j] < arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}