Previous Lecture Lecture 12 Next Lecture

Lecture 12, Thu 05/11

Quadratic Sorting Algorithms cont.

Recorded Lecture: 5_11_23

Selection Sort

Idea: Similar to Bubble Sort, we make passes through the list and find the largest element. We then swap the largest element in the correct place (each iteration will place the largest element at the end of the list assuming we’re sorting in ascending order)

def selectionSort(aList):
	for fillslot in range(len(aList)-1,0,-1):
		positionOfMax=0
		for location in range(1,fillslot+1):
			if aList[location]>aList[positionOfMax]:
				positionOfMax = location

		# swap largest element in correct place
		temp = aList[fillslot]
		aList[fillslot] = aList[positionOfMax]
		aList[positionOfMax] = temp
def test_selectionSort():
	list1 = [1,2,3,4,5,6]
	list2 = [2,2,2,2,2,2]
	list3 = []
	list4 = [6,7,5,3,1]
	selectionSort(list1)
	assert list1 == [1,2,3,4,5,6]
	selectionSort(list2)
	assert list2 == [2,2,2,2,2,2]
	selectionSort(list3)
	assert list3 == []
	selectionSort(list4)
	assert list4 == [1,3,5,6,7]

Selection Sort Analysis

Insertion Sort

Idea: We want to work left-to-right and insert unsorted elements into the sorted left portion of the list

Analogy: Similar to how one might sort a deck of cards * Work left-to-right, take a card and “insert” it into the correct position on the left portion of the sorted deck

def insertionSort(aList):
	for index in range(1,len(aList)):

		currentvalue = aList[index]
		position = index

		# shift elements over by one
		while position > 0 and aList[position-1] > currentvalue:
			aList[position] = aList[position-1]
			position = position-1

		# insert element in appropriate place
		aList[position] = currentvalue
def test_insertionSort():
	list1 = [1,2,3,4,5,6]
	list2 = [2,2,2,2,2,2]
	list3 = []
	list4 = [6,7,5,3,1]
	insertionSort(list1)
	assert list1 == [1,2,3,4,5,6]
	insertionSort(list2)
	assert list2 == [2,2,2,2,2,2]
	insertionSort(list3)
	assert list3 == []
	insertionSort(list4)
	assert list4 == [1,3,5,6,7]

Insertion Sort Analysis