liveBook · Manning

Dataset split

As explained in Grokking Algorithms, Second Edition

Partitioning is the process of dividing a sequence around a selected pivot into groups based on their comparison with the pivot.

Partitioning splits an array around a chosen pivot, grouping other elements by comparison with it. In quicksort, the resulting groups are sorted recursively and joined with the pivot. section 4.2

To partition as part of quicksort:

  • Choose a pivot from the array. section 4.2
  • Group the remaining elements by comparing them with the pivot. section 4.2
  • Sort each group recursively, then combine the sorted groups with the pivot. section 4.2

A pivot divides an array

For [10, 5, 2, 3], the code chooses 10 as the pivot and places 5, 2, and 3 in the lower group; the greater group is empty. section 4.2

def quicksort(array):
  if len(array) < 2:
    return array                                  #1
  else:
    pivot = array[0]                              #2
    less = [i for i in array[1:] if i <= pivot]   #3
    
    greater = [i for i in array[1:] if i > pivot] #4

    return quicksort(less) + [pivot] + quicksort(greater)

print(quicksort([10, 5, 2, 3]))
#1 Base case: arrays with 0 or 1 element are already sorted.
#2 Recursive case
#3 Sub-array of all the elements less than the pivot
#4 Sub-array of all the elements greater than the pivot

Python quicksort code shows the base case, pivot choice, group construction, and recursive calls. section 4.2

How Grokking Algorithms, Second Edition covers it

How deep it goes
Works through pivot selection, grouping, and recursive sorting, but defers how to choose a good pivot.
Examples
Uses small arrays, including [10, 5, 2, 3] and a three-element example with pivot 33.
What you can do after
Apply the pivot-and-group step within a recursive quicksort procedure.
How it connects
Connects partitioning to quicksort, recursion, base cases, and divide-and-conquer.

Also explained in

Compare how 21 books explain dataset split →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Algorithms, Second Edition. The section links point to the parts of the book it draws on.