Computer Science Notes

Notes From CS Undergrad Courses FSU

This project is maintained by awa03

Quick Sort

Given array S to be sorted • If size of S < 1 then done; • Pick any element v in S as the pivot • Partition S-{v} (remaining elements in S) into two groups • S1 = {all elements in S-{v} that are smaller than v} • S2 = {all elements in S-{v} that are larger than v} • Return {quicksort(S1) followed by v followed by quicksort(S2) } • Trick lies in handling the partitioning (step 3). • Picking a good pivot • Efficiently partitioning in-place

![[Difference-Between-Quicksort-and-Merge-Sort_Figure-1.webp]]

Picking the Pivot

Example

• Example: Median-of-three Partitioning – Let input S = {6, 1, 4, 9, 0, 3, 5, 2, 7, 8} – left=0 and S[left] = 6 – right=9 and S[right] = 8 – center = (left+right)/2 = 4 and S[center] = 0 – Pivot • = Median of S[left], S[right], and S[center] • = median of 6, 8, and 0 • = S[left] = 6

Partitioning Algorithm

While (i < j)
	Move i to the right till we find a number greater than pivot
	Move j to the left till we find a number smaller than pivot
	If (i < j) swap(S[i], S[j])
//(The effect is to push larger elements to the right and smaller elements to the left)
Swap the pivot with S[i]

When Dealing With Small Arrays

Code Examples

template <typename Comparable>
void quicksort( vector<Comparable> & a, int left, int right )
{
	if( left + 10 <= right )
	{
		const Comparable & pivot = median3( a, left, right ); 
		// Begin partitioning
		int i = left, j = right - 1;
		for( ; ; ) {
			while( a[ ++i ] < pivot ) { }
			while( pivot < a[ --j ] ) { }
			if( i < j )
				std::swap( a[ i ], a[ j ] );
			else
				break;
	}
	std::swap( a[ i ], a[ right - 1 ] ); // Restore pivot
	quicksort( a, left, i - 1 ); // Sort small elements
	quicksort( a, i + 1, right ); // Sort large elements
	}
	else // Do an insertion sort on the subarray
		insertionSort( a, left, right )
}

Runtime


Linear Time Sorts

Bucket Sort

Radix Sort