quickSort Algorithm 1. If first < last then begin 2. Partition the elements in the subarray first..last so that the pivot value is in place (in position pivIndex) 3. Apply quickSort to the first subarray first..pivIndex-1 4. Apply quickSort to the second subarray pivIndex+1..last end The two stopping cases are: 1. (first = last) -- only one value in subarray so sorted! 2. (first > last) -- no values in subarray so sorted!
How do we Partition? 1. Define the pivot value as the contents of val[first] 2. Initialize up to first and uown to last 3. Repeat 4. Increment up until up selects the first element greater than the pivot value 5. Decrement down until it selects the first element less than or equal to the pivot value 6. if up < down exchange their values until up meets or passes down 7. Exchange val[first] and val[down] 8. Define pivIndex as down
quickSort Example firstlast
Has first exceeded last? firstlast
Has first exceeded last? firstlast NO!
Define the value in position first to be the pivot firstlast
Define the value in position first to be the pivot firstlast pivot
Define up to be first and down to be last firstlast pivot
Define up to be first and down to be last updown pivot 44 firstlast
Move up to the first value > pivot updown pivot 44 firstlast
Move up to the first value > pivot updown pivot 44 firstlast
Move down to the first value <= pivot updown pivot 44 firstlast
Move down to the first value <= pivot updown pivot 44 firstlast
Exchange these values updown pivot 44 firstlast
Exchange these values updown pivot 44 firstlast
Move up to the first value > pivot updown pivot 44 firstlast
Move up to the first value > pivot updown pivot 44 firstlast
Move down to the first value <= pivot updown pivot 44 firstlast
Move down to the first value <= pivot updown pivot 44 firstlast
Exchange them updown pivot 44 firstlast
Move up to the first value > pivot updown pivot 44 firstlast
Move up to the first value > pivot updown pivot 44 firstlast
Move down to the first value <= pivot updown pivot 44 firstlast
Move down to the first value <= pivot updown pivot 44 firstlast
up and down have passed each other, so exchange the pivot value and the value in down updown pivot 44 firstlast
up and down have passed each other, so exchange the pivot value and the value in down updown pivot 44 firstlast
up and down have passed each other, so exchange the pivot value and the value in down pivIndex down pivot 44 firstlast
Note that all values below pivIndex are <= pivot pivIndex pivot 44 firstlast
and all values above pivIndex are > pivot pivIndex pivot 44 firstlast
This gives us two new subarrays to Partition pivIndex pivot 44 first 1 last 2 first 2 last
quickSort Procedure Code public void quickSort ( int [ ] a, int first, int last ) { int pivIndex; if ( first < last ) { pivIndex = partition ( a, first, last ); quickSort ( a, first, pivIndex-1 ); quickSort ( a, pivIndex+1, last ); }