Classic algorithms · 18 / 22 Exercise Hard

Quicksort

Objective

Quicksort chooses a pivot, separates the other elements into smaller and larger than it, and sorts each group recursively. It is usually very fast, but it depends on how well the pivot is chosen.

Instructions

  • Read a line with integers separated by spaces.
  • Define quicksort(items): a list of 0 or 1 elements is already sorted. Otherwise, the pivot is the first element; separate all the elements into smaller (smaller than the pivot), equal (equal, including the pivot itself) and larger (larger).
  • The result is quicksort(smaller) + equal + quicksort(larger). Count how many times quicksort is called in total, including the calls with empty or one-element lists.
  • Show the sorted list and, on another line, Calls: k.
Input
5 2 4 7 1 3
Output
1 2 3 4 5 7
Calls: 7

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise