The pseudocode of a function is given below:
fun(int A[0,....,n-1]) {
for i=0 to n-2
for j=0 to n-i-2
if (A[j]>A[j+1])
then swap A[j] and A[j+1]
}Let be an array storing distinct integers in descending order. The number of swap operations that will be performed, if the function is called with as argument, is _________. (Answer in integer)
View worked solution
Answer: 435:435
The given pseudocode implements the standard Bubble Sort algorithm:
fun(int A[0,....,n-1]) {
for i=0 to n-2
for j=0 to n-i-2
if (A[j] > A[j+1])
then swap A[j] and A[j+1]
}
For an array of size , the outer loop runs for from to . For each , the inner loop runs for from to .
Since the array of size is initially sorted in descending order with distinct elements, every comparison A[j] > A[j+1] will evaluate to true. Thus, a swap operation is performed during every single comparison.
The total number of swaps is the sum of the number of inner loop iterations across all outer loop steps:
Substituting into the formula:
Therefore, the number of swap operations performed is 435.
Free practice · Your answers on this page are not saved.
