Previous Lecture Lecture 14 Next Lecture

Lecture 14, Thu 05/18

Quicksort, Trees

Recorded Lecture: 5_18_23

Quicksort

How do we partition the list into left / right sub lists?

  1. Choose pivot (typically first element in list)
  2. leftmark index is on left-most side of list, rightmark index is on right-most side of list, and both leftmark and rightmark work inwards
  3. Find an element in the left side (using leftmark index) that’s out-of-place (> pivot)
  4. Find an element in the right side (using rightmark index) that’s out-of-place (< pivot)
  5. Swap out-of-place elements with each other
    • We’re putting them in the correct side of the list!
  6. Continue doing steps 1 - 5 until the rightmark index < leftmark index
  7. Swap the pivot with rightmark index
    • We’re putting the pivot element in the correct place!

Quick Sort Hand Drawn Example

quicksortExample.png

Quick Sort Implementation

def quickSort(alist):
	quickSortHelper(alist, 0, len(alist) - 1)

# helper function so we can pass in the first / last index
# of lists
def quickSortHelper(alist, first, last):
	if first < last:

		# will define the indices of the left / right sub lists
		splitpoint = partition(alist, first, last)

		# recursively sort the left / right sub lists
		quickSortHelper(alist, first, splitpoint-1) # left
		quickSortHelper(alist, splitpoint+1, last) # right

# partition function will organize left sublist < pivot
# and right sub list > pivot
def partition(alist, first, last):
	pivotvalue = alist[first] # choose first element as pivot

	leftmark = first + 1
	rightmark = last

	done = False
	while not done:

		# move leftmark until we find a left element > pivot
		while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
			leftmark = leftmark + 1

		# move rightmark until we find a right element < pivot
		while rightmark >= leftmark and alist[rightmark] >= pivotvalue:
			rightmark = rightmark - 1

		# check if we're done swapping left / right elements in
		# correct side
		if rightmark < leftmark:
			done = True
		else: # swap left and right elements into correct side of list
			temp = alist[leftmark]
			alist[leftmark] = alist[rightmark]
			alist[rightmark] = temp

	# put the pivot value into the correct place (swap pivot w/ rightmark)
	temp = alist[first] # pivot
	alist[first] = alist[rightmark]
	alist[rightmark] = temp

	return rightmark

Quick Sort Analysis

quicksortAnalysis.png

Trees

Terminology