The pseudocode of a function fun() is given below: Let π΄[0, β¦ ,29] be an array storing 30 distinct integers in descending order. The number of swap operations that will be performed, if the function fun() is called with π΄[0, β¦ ,29] as argument, is __________. (Answer in integer)
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]
}
To determine the number of swap operations performed by the function fun(), recognize that it implements a variation of the Bubble Sort algorithm. Given an array A[0, β¦, 29] sorted in descending order, we need to calculate the swaps to sort it in ascending order. Here's how:
Understanding Bubble Sort: The nested loops ensure that in each iteration of the outer loop, the largest element in the unsorted portion is "bubbled" to the end.
Loop Analysis: The outer loop runs from 0 to n-2 (i.e., 28), and the inner loop runs from 0 to n-i-2.
Initial State: The array is in descending order, requiring swaps at every comparison to sort ascendingly.
Counting Swaps: We can compute the swaps by summing the elements from 1 to n-1 since initially every pair (A[j], A[j+1]) is in the wrong order:
\(Total\ Swaps=\sum_{i=1}^{29}i=\frac{29\times(29+1)}{2}=435\)
Verification: The computed value, 435, fits the expected range (435,435).
Therefore, the function performs 435 swaps.
What is the worst case time complexity of bubble sort?
Any decision tree that sorts n elements has height
You have to sort a list L, consisting of a sorted list followed by a few βrandomβ elements. Which of the following sorting method would be most suitable for such a task ?
If there are n integers to sort, each integer has d digits and each digit is in the set {1, 2, ..., k}, radix sort can sort the numbers in :