CIS 3130
Data Structures
Lecture 4
Algorithmic Analysis


Overview

What is the point of multiple implementations?

Criteria for comparing implementations/algorithms

Factors affecting algorithm and performance

Algorithmic Analysis

The complexity of an algorithm is a measure of how much time or space the algorithm takes in proposition to the size of the input. Algorithmic analysis is the evaluation of an algorithm for the purpose of determining its complexity. Algorithmic Analysis is:

Some Examples

Linear Search of an Array

bool linearSearch(int arr, int n, int val) {
	for (int i = 0; i < n; i++)
		if (arr[i] == val) return true;
	return false;	
}

Simple-minded Bubble Sort of an Array

void bubbleSort(int arr, int n) {
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n-1; j++)
			if (arr[j] > arr[j+1]) {
				int t = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = t;
			}
}

Selection Sort of an Array

void selectionSort(int arr, int n) {
	for (int last = n-1; last > 0; last--) {
		int maxPos = 0;
		for (int j = 1; j < last; j++)
			if (arr[j] > arr[maxPos]) maxPos = j;
		int t = arr[maxPos];
		arr[maxPos] = arr[last];
		arr[last] = t;
	}
}

Binary Search of an Array

bool binarySearch(int arr, int lo, int hi, int val) {
	if (lo > hi) return false;
	mid = (lo + hi) / 2;
	if (arr[mid] == val) 
		return true;
	else if (arr[mid] < val) 
		return binarySearch(arr, mid+1, hi, val);
	else 
		return binarySearch(arr, lo, mid-1, val);
}

Accessing the i'th Element of an Array

int arr[10];
…
… = arr[i];
…

Finding the Minimum of an Unsorted Array

int getMin(int arr, int n) {
	for (int i = 1; i < n; i++)
		if (arr[i] < min) min = ar[i];
	return min;
}		

Finding the Minimum of an Sorted Array

int getMin(int arr, int n) {
	return arr[0];
}		

Removing an Element from an Unsorted Array

int remove(int arr, int &size, int index) {
	for (int i = index; i < size-1; i++)
		arr[i] = arr[i+1];
	size--;
}
linear (order n)
int remove(int arr, int size, int index) {
	arr[index] = arr[size-1];
	size--;
}
constant (order 1)

Observations

Big O Notation

Common Orders

Order notation n=1 n=10 n=100 n=1000
Constant O(1) 1 1 1 1
LogarithmicO(log2n) 0 ~3 ~6 ~10
Linear O(n) 1 10 100 1,000
Loglinear/LinearithmicO(nlog2n) 0 ~30 ~600 ~10,000
Quadratic O(n2) 1 100 10,000 1,000,000
Cubic O(n3) 1 1,000 1,000,000 1,000,000,000
ExponentialO(an often a=2) 2 1000    

Comparing the Orders and their Growths

Here is a series of graphs and their data points to help understand compare the adjacent orders and also in order to understand the effect of the coefficients on each order.

Here is a series of graphs to help get a better sense of the relative growth of the above values (and therefore the relative performances of algorithms of the various orders), and the relative effect of coefficients on the adjacent orders.

Amortized Time

Summary (Yanosky's 4 Rules)

An Algorithmic Analysis Cheat Sheet