CIS 3130
Data Structures
Sorting


Overview

Some Concepts

Bubble Sort

Cost?
sort(a[0 ... n-1]) {
	for (last = n-1 ... 1)
		for (i = 0 ... last-1)
			if (a[i] > a[i+1]) swap them
}

An optimization

Cost?
sort(a[0 ... n-1]) {
	for (last = n-1 ... 1 && swapped an element last time through)
		for (i = 0 ... last-1)
			if (a[i] > a[i+1]) swap them
}

Insertion sort

Cost?
sort(a[0 ... n-1]) {
	for (next = 1 ... n-1) {
		hold onto a[next]
		for (i = next-1 ... 0 && a[i] > held item)
			slide a[i] one position to right
		place held item into a[i+1]
	}
}

Selection Sort

Cost?
sort(a[0 ... n-1])
{
	for (last = n-1 ... 1)
		find largest element in a[0 ... last]
		swap with a[last]
}

Quicksort

sort(a[lb ... ub]) {
	if (lb >= ub) done
	pos = position where placed chosen element in a[lb ... ub]
	sort(a[lb ... pos-1]);
	sort(a[pos+1 ... ub]);
}
Cost?

Heapsort

Preliminaries The basic idea: Making it efficient The actual algorithm:
sort(a[0 ... n-1) {
	for (i = n/2-1 ... 0)
		adjust a[i ... n-1] so it becomes a heap

	for (last = n-1 ... 1)
		swap a[0] a[last]);
		adjust a[0 ... last-1] so it becomes a heap
}
Cost?

Code for Sorting