The quicksort algorithm sorts an array by recursively dividing it into smaller sub-arrays by picking a pivot element. It partitions the array into two halves based on the pivot, putting elements less than the pivot in one half and greater elements in the other. The process is then repeated on each sub-array until the entire array is sorted. It works by first choosing a pivot element, partitioning the array around the pivot so that elements less than the pivot come before elements greater than it, and then quicksorting the two resulting sub-arrays.
1 of 31
Downloaded 19 times
More Related Content
Quicksort algorithm
1. Quicksort Algorithm
Given an array of n elements (e.g., integers):
If array only contains one element, return
Else
pick one element to use as pivot.
Partition elements into two sub-arrays:
Elements less than or equal to pivot
Elements greater than pivot
Quicksort two sub-arrays
Return results
3. Pick Pivot Element
There are a number of ways to pick the pivot element. In this
example, we will use the first element in the array:
40 20 10 80 60 50 7 30 100
4. Partitioning Array
Given a pivot, partition the elements of the array
such that the resulting array consists of:
1. One sub-array that contains elements >= pivot
2. Another sub-array that contains elements < pivot
The sub-arrays are stored in the original data array.
Partitioning loops through, swapping elements
below/above pivot.