You are on page 1of 2

Question No.

1
What exactly the following algorithm is doing? Explain the working of algorithm with an example, the size of array is 10. Moreover perform asymptotic analysis of the given algorithm.
Void Algo01 (Input Array A) intMinPos, temp, i, j; for(i = n-1; i > 0; i--) MinPos = i; for ( j = 0; j < i; j++) If ( A[ j ] < A[ MinPos ]) MinPos = j; Temp = A[ i ]; A[ i ] = A[ MinPos ]; A[MinPos ] = temp;

Answer:This is a sorting algorithm. This type of sorting is called "Selection Sort" in descending order because it works by selecting the smallest element of the array and placing it at the tail of the array. Then this process is repeated for the remainder of the array. It works as follows: first find the smallest element in the array and exchange it with the element in the last position, then find the second smallest element and exchange it with the element in the second last position, and continue in this way until the entire array is sorted in descending order. The algorithm works as follows: 1. Set last position of array as current position. 2. Find the minimum value in the list 3. Swap it with the value in the current position 4. Set next position (towards start of array) as current position 5. Repeat Steps 2-4 until you reach the start of list Example:-

Algorithm
Void Algo01 (Input Array A) intMinPos, temp, i, j; for (i = n-1; i > 0; i--) MinPos = i; for ( j = 0; j < i; j++) If ( A[ j ] < A[ MinPos ]) MinPos = j; Temp = A[ i ]; A[ i ] = A[ MinPos ]; A[MinPos ] = temp;

Cost
c1 c2 c3 c4 c5 c6 c7 c8 c9

Times
1 1 n (n-1) n(n-1) (n-1)(n-1) (n-1) (n-1) (n-1)

So the total running time is T (n) = c1(1) + c2(1) + c3(n) + c4(n-1) + c5(n(n-1)) + c6((n-1)(n-1)) + c7(n-1) + c8(n-1) + c9(n-1) = c1 + c2 + c3n + c4n c4 + c5n2 c5n + c6 n2 2c6n + c6 + c7n c7 + c8n c8 + c9n c9 = c5n2 + c6 n2 + c3n + c4n c5n 2c6n + c7n + c8n + c9n + c1 + c2 c4 + c6 c7 c8 c9 T (n) = n2 (c5 + c6) + n (c3 + c4 c5 2c6 + c7 + c8 + c9) + (c1 + c2 c4 + c6 c7 c8 c9) So the T (n) equation is similar to an2+bn+c Then the asymptotic notation will be (n2).

You might also like