Designing and Analyzing Algorithms




CS146

Chris Pollett

Feb 5, 2014

Outline

Insertion Sort as Code

Original Pseudo-Code

1 for j=2 to A.length
2     key = A[j]
3     // Insert A[j] into the sorted sequence A[1..j-1]
4     i = j - 1
5     while i > 0 and A[i] > key
6         A[i+1] = A[i]
7         i = i - 1
8     A[i + 1] = key

Working Python Code

import sys

def insertion_sort(A):
    for j in range(1, len(A)):
        key = A[j]
        # Insert A[j] into the sorted sequence A[0:j-2]
        i = j - 1
        while i >= 0 and A[i] > key:
            A[i + 1] = A[i]
            i = i - 1
        A[i + 1] = key

if len(sys.argv) < 2:
    print "Enter some numbers to sort"
    raise SystemExit(1)
A = sys.argv[1:];
for i in range(0,len(A)):
    try:
        A[i] = int(A[i])
    except ValueError:
        print "Items to sort must be integers"
        raise SystemExit(1)
insertion_sort(A);
print A;

Insertion Sort in Java

public class InsertionSort
{
    public static void sort(int[] A)
    {
        for(int j = 0; j < A.length; j++)
        {
            int key = A[j];
            // Insert A[j] into the sorted sequence A[0], A[1], ... A[j-1]
            int i = j - 1;
            while(i >= 0 && A[i] > key)
            {
                A[i + 1] = A[i];
                i = i - 1;
            }
            A[i + 1] = key;
        }
    }

    public static void main(String args[])
    {
        if(args.length < 1)
        {
            System.out.println("Enter some numbers to sort");
            System.exit(1);
        }

        int[] A = new int[args.length];
        try
        {
            for(int j = 0; j < args.length; j++)
            {
                A[j] = Integer.parseInt(args[j]);
            }
        }
        catch (NumberFormatException e)
        {
            System.out.println("Items to sort must be integers");
            System.exit(1);
        }
        sort(A);

        String space = "";
        for(int key: A)
        {
            System.out.print(space + key);
            space = " ";
        }
        System.out.print("\n");
    }
}

Analyzing Algorithms

Measuring the time of an Algorithm

Analyzing INSERTION-SORT -- Best Case

The number of times each line of insertion sort executes

Worst Case analysis

What case should we look at?

Orders of Growth