



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Constant Time: O(1)
Constant Loop: O(1)
operations within loop are constant:
public class CardDeck { CardDeck() { int topCard = 0; for(int i=0; i < 13; i++) { cards[topCard++] = new Card(Card.diamond, i); cards[topCard++] = new Card(Card.club, i); cards[topCard++] = new Card(Card.spade, i); cards[topCard++] = new Card(Card.heart, i); } } }
13 * 4 constant operations constant time O(1)
Nested Loops: Independent
void matrixMult(double [][] a, double [][] b, double [][] c){ int n = a.length; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { c[i][j] = 0.0; for(int k = 0; k < n; k++) { c[i][j] += a[i][k] * b[k][j]; } } } }
n
n
n
= n^3
O( n^3 )
Nested Loops: Dependent
void bubbleSort(double [] v) { int n = v.length;
// Find largest remaining value and place in v[i]. for (int i = n - 1; i > 0; i--) {
// Move large values to the top. for (int j = 0; j < i; j++) { if (v[j] > v[j+1]) { // If out of order, double temp = v[j]; // then swap. v[j] = v[j + 1]; v[j + 1] = temp; } } }
While Loops: Simple Case
void insertionSort(double [] v) { int n = v.length; for(int i = 1; i < n; i++) {
// Move element v[i] into place. double element = v[i]; int j = i - 1; while (j >= 0 && element < v[j]) { v[j+1] = v[j]; j--; // Slide old value up. } v[j+1] = element; } }
While Loops: Binary Subdivision
int binarySearch(double [] data, double val) { int mid, low = 0, high = data.length;
// Iteratively subdivide the search area until only one value left. while (low < high) { mid = (low + high) / 2; if (data[mid] < val) low = mid + 1; else high = mid; } return low; }
Benchmarking
final word