Open In App
Related Articles

Algorithms | Sorting | Question 1

Improve Article
Save Article
Like Article

What is recurrence for worst case of QuickSort and what is the time complexity in Worst case?
(A) Recurrence is T(n) = T(n-2) + O(n) and time complexity is O(n^2)
(B) Recurrence is T(n) = T(n-1) + O(n) and time complexity is O(n^2)
(C) Recurrence is T(n) = 2T(n/2) + O(n) and time complexity is O(nLogn)
(D) Recurrence is T(n) = T(n/10) + T(9n/10) + O(n) and time complexity is O(nLogn)

Answer: (B)

Explanation: The worst case of QuickSort occurs when the picked pivot is always one of the corner elements in sorted array. In worst case, QuickSort recursively calls one subproblem with size 0 and other subproblem with size (n-1). So recurrence is

T(n) = T(n-1) + T(0) + O(n)

The above expression can be rewritten as

T(n) = T(n-1) + O(n)

void exchange(int *a, int *b)
  int temp;
  temp = *a;
  *a   = *b;
  *b   = temp;
int partition(int arr[], int si, int ei)
  int x = arr[ei];
  int i = (si - 1);
  int j;
  for (j = si; j <= ei - 1; j++)
    if(arr[j] <= x)
      exchange(&arr[i], &arr[j]);
  exchange (&arr[i + 1], &arr[ei]);
  return (i + 1);
/* Implementation of Quick Sort
arr[] --> Array to be sorted
si  --> Starting index
ei  --> Ending index
void quickSort(int arr[], int si, int ei)
  int pi;    /* Partitioning index */
  if(si < ei)
    pi = partition(arr, si, ei);
    quickSort(arr, si, pi - 1);
    quickSort(arr, pi + 1, ei);

Quiz of this Question

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads