Skip to content
Related Articles

Related Articles

GATE | GATE-CS-2016 (Set 2) | Question 23
  • Last Updated : 13 Feb, 2016

Assume that the algorithms considered here sort the input sequences in ascending order. If the input is already in ascending order, which of the following are TRUE ?

I.   Quicksort runs in Θ(n2) time
II.  Bubblesort runs in Θ(n2) time
III. Mergesort runs in  Θ(n) time
IV.  Insertion sort runs in  Θ(n) time 

(A) I and II only
(B) I and III only
(C) II and IV only
(D) I and IV only

Answer: (D)

Explanation: I. Given an array in ascending order, Recurrence relation for total number of comparisons for quicksort will be
T(n) = T(n-1)+O(n) //partition algo will take O(n) comparisons in any case.
= O(n^2)

II. Bubble Sort runs in Θ(n^2) time

If an array is in ascending order, we could make a small modification in Bubble Sort Inner for loop which is responsible for bubbling the kth largest element to the end in kth iteration. Whenever there is no swap after the completion of inner for loop of bubble sort in any iteration, we can declare that array is sorted in case of Bubble Sort taking O(n) time in Best Case.

III. Merge Sort runs in Θ(n) time
Merge Sort relies on Divide and Conquer paradigm to sort an array and there is no such worst or best case input for merge sort. For any sequence, Time complexity will be given by following recurrence relation,

T(n) = 2T(n/2) + Θ(n) // In-Place Merge algorithm will take Θ(n) due to copying an entire array.
= Θ(nlogn)

IV. Insertion sort runs in Θ(n) time

Whenever a new element which will be greater than all the elements of the intermediate sorted sub-array ( because given array is sorted) is added, there won’t be any swap but a single comparison. In n-1 passes we will be having 0 swaps and n-1 comparisons.
Total time complexity = O(n) // N-1 Comparisons

This solution is contributed by Pranjul Ahuja

For an array already sorted in ascending order,
Quicksort has a complexity Θ(n2) [Worst Case]
Bubblesort has a complexity Θ(n) [Best Case]
Mergesort has a complexity Θ(n log n) [Any Case]
Insertsort has a complexity Θ(n) [Best Case]

Quiz of this Question


My Personal Notes arrow_drop_up
Recommended Articles
Page :