151 views
0 0 votes

Consider the Quick sort algorithm which sorts elements in ascending order using the first element as pivot. 

Then which of the following input sequence will require a maximum number of comparisons when this algorithm is applied on it?

  1. $\text{22 25 56 67 89}$
     
  2. $\text{52 25 76 67 89}$
     
  3. $\text{22 25 76 67 50}$
     
  4. $\text{52 25 89 67 76}$

1 Answer

0 0 votes

Quicksort uses the first element as pivot.

The maximum number of comparisons occurs when each partition is as unbalanced as possible.

Option (A) is:

$22,25,56,67,89$

This array is already sorted.

The first pivot is $22$, which is the smallest element.

Therefore, the partition sizes are: $0$ and $4$

The next pivot is $25$, again the smallest element of the remaining subarray.

The partition sizes become: $0$ and $3$

This continues throughout the algorithm.

The comparisons are therefore: $4+3+2+1=10$

In general, for $n$ elements:

$(n-1)+(n-2)+\cdots+1=\frac{n(n-1)}{2}$

Thus, an already sorted array produces the maximum number of comparisons when the first element is always selected as pivot.

Answer:
Position:
Show:

Related questions

1 1 vote
1 1 answer
160
160 views
GO Classes asked Aug 10
160 views
While sorting the numbers $\text{(70, 48, 76, 58, 43, 47, 78, 53)}$ using quicksort, the last number is chosen as pivot, what will be the permutation of the numbers after...
0 0 votes
1 1 answer
175
175 views
GO Classes asked Aug 8
175 views
The best case behaviour occurs for quick sort is, if partition splits the array of size $n$ into$n/2:(n/2)-1$ $n/2:n/3$ $n/4:3n/2$ $n/4:3n/4$
0 0 votes
1 1 answer
132
132 views
GO Classes asked Aug 8
132 views
Which of the following is correct with regard to insertion sort?insertion sort is stable and it sorts In-place insertion sort is unstable and it sorts In-place insertion ...
0 0 votes
1 1 answer
154
154 views
GO Classes asked Aug 10
154 views
Which of the following algorithms is better when dealing with reverse sorted numbers?Quicksort Heap sort Insertion sort all are equally good