Category Archives: Homework

Selection Sort Exercises

November 10th, 2015

Screen Shot 2014-11-16 at 3.06.54 PM

Go to classroom Salon – Selection Sort Video

Classwork:
1. Show, in the style of the example trace with the given implementation,how selection sort sorts the array E A S Y Q U E S T I O N.

2. What is the maximum number of exchanges involving any particular element during selection sort? What is the average number of exchanges involving an element?

3. Give an example of an array of N items that maximizes the number of times the test a[j] < a[min] fails (and, therefore, min gets updated) during the operation of selection sort (given implementation).

AOA: Local minimum of a matrix

October 15th, 2014

Screen Shot 2014-10-12 at 11.03.54 PM

Classwork:
Previous assignments discussions in class and Classroom Salon.

Homework:
Local minimum of a matrix. Given an N-by-N array a[] of N^2 distinct integers, design an algorithm that runs in time proportional to N to find a local minimum: a pair of indices i and j such that a[i][j] < a[i+1][j], a[i][j] < a[i][j+1], a[i][j] < a[i-1][j], and a[i][j] < a[i][j-1]. The running time of your program should be proportional to N in the worst case.

Insertion and Selection sorts

November 3rd, 2015

Screen Shot 2014-11-16 at 3.06.54 PM

The insertion and selection sorts
Why study them:

  • They are playground where can learn terminology and basic mechanisms.
  • simple algorithms are more effective in some applications than the sophisticated algorithms that we shall discuss later.
  • They are useful in improving the efficiency of more sophisticated algorithms.

 
The objective of the sorting algorithm is to rearrange the items such that their keys are ordered according to some well-defined ordering rule (usually numerical or alphabetical order).

In Java, items are just objects, and the abstract notion of a key is captured in a built-in mechanism—the Comparable interface.

PU COS 226 call different implementations by name: Insertion.sort(), Merge.sort(), Quick.sort(), and so forth. With less() and exch() as their main methods. These sort methods are effective for any type of data that implements Comparable

“Restricting data access to these two operations makes our code readable and portable, and makes it easier for us certify that algorithms are correct, to study performance and to compare algorithms.” R.S.


Template for sort classes

public class Example
  {
     public static void sort(Comparable[] a)
     {  
       /* Sorts */  
      }

     private static boolean less(Comparable v, Comparable w)
     {  
       return v.compareTo(w) < 0;
     }

     private static void exch(Comparable[] a, int i, int j)
     {  
       Comparable t = a[i]; 
       a[i] = a[j]; 
       a[j] = t;  
     }

     private static void show(Comparable[] a)
     {  
       // Print the array, on a single line.
        for (int i = 0; i < a.length; i++)
           StdOut.print(a[i] + " ");
        StdOut.println();
     }

     public static boolean isSorted(Comparable[] a)
     {  // Test whether the array entries are in order.
        for (int i = 1; i < a.length; i++)
           if (less(a[i], a[i-1]))  
              return false;
        return true;
     }

     public static void main(String[] args)
     {  
      // Read strings from standard input, sort them, and print.
        String[] a = In.readStrings();
        sort(a);
        assert isSorted(a);
        show(a);
    } 
}


Screen Shot 2014-11-16 at 3.34.47 PM

Questions to answer:

  • Certification: Does the sort implementation always put the array in order, no matter what the initial order?
  • Running time: What is the running time,cost model ,and algorithm performance?
  • Extra Memory: What is the amount of extra memory used by a sorting algorithm?
  • Data type: What type of data item can be sorted?

Selection sort One of the simplest sorting algorithms works as follows: First, find the smallest item in the array and exchange it with the first entry (itself if the first entry is already the smallest). Then, find the next smallest item and exchange it with the second entry. Continue in this way until the entire array is sorted. This method is called selection sort because it works by repeatedly selecting the smallest remaining item.

Proposition A. Selection sort uses ~N^2/2 compares and N exchanges to sort an array of length N.


public class Selection
  {

    private static boolean less(Comparable v, Comparable w)
    {  
    	return v.compareTo(w) < 0; 
    }
    
    private static void exch(Comparable[] a, int i, int j)
    {  
    	Comparable t = a[i]; 
    	a[i] = a[j]; 
    	a[j] = t;  
    }
    
    private static void show(Comparable[] a)
    {  // Print the array, on a single line.
       for (int i = 0; i < a.length; i++)
          StdOut.print(a[i] + " ");
       StdOut.println();
}
    public static boolean isSorted(Comparable[] a)
    {  // Test whether the array entries are in order.
       for (int i = 1; i < a.length; i++)
          if (less(a[i], a[i-1]))  return false;
       return true;
    }
     public static void sort(Comparable[] a)
     {  
    	 // Sort a[] into increasing order.
        int N = a.length;               // array length
        for (int i = 0; i < N; i++)
        {  // Exchange a[i] with smallest entry in a[i+1...N).
           int min = i;                 // index of minimal entr.
           for (int j = i+1; j < N; j++)
              if (less(a[j], a[min])) 
            	  min = j;
           exch(a, i, min);
        }         
     }
     
     public static void main(String[] args)
     {  
    	 // Read strings from standard input, sort them, and print.
        String[] a = In.readStrings();
        sort(a);
        assert isSorted(a);
        show(a);
     }
}
  • Running time is insensitive to input.
  • Data movement is minimal.

Classwork:
Watch video and comment on questions in Classroom Salon.

Homework:
Prove the selection sort efficiency mathematically or show by examining the tracing or by one of the techniques you learned in the Analysis of Algorithms section in chapter 1.

AOA: Order Of Growth

November 2nd, 2015

Screen Shot 2014-10-12 at 11.03.54 PM

Classwork:
Classroom Salon – Videos 2.3 and 2.4

Order-Of_growth
1. Describe the last column for each order-of-growth.

2. Give the code for each of the order-of-growth classifications:
constant, logarithmic, linear, linearithmic, quadratic, and cubic.

3. Give the description and example for each of the order-of-growth classifications.

4. Which of the following order-of-growth classifications represents the maximum number of array accesses used to binary search a sorted array of size N?
a. constant
b. logarithmic
c. linear
d. linearithmic

Theory of Algorithms
1. What is Big Theta used for?
2. What is Big Oh used for?
3. What is Big Omega for?

4. Explain the differences and similarities between the three different sum programs and the three Big notations.

5. What are the 2 caveats mentioned int he video?

Homework:
Complete posted assignments

AOA: function of N

October 28th, 2015

Screen Shot 2014-10-12 at 11.03.54 PM

Classroom Salon: Video 2.3: Order of Growth

Visit edmodo.com:
1.
Quiz
How many accesses does the following code fragment make as a function of N?
(Assume the compiler does not optimize away any array accesses int eh innermost loop)


int sum = 0;
for (int i = 0; i < N ; i++ )
---> for (int j = i + 1; j < N ; j++ ) 
--------> for (int k = 1; k < N ; k = k*2 )
------------> if ( a[i] + a[j] >= a[k]) sum++;


~3N^2
~(3/2)N^2 lgN
~(3/2)N^3
~3N^3

2.
Proposition: Binary search uses at most 1 + lgN compares to search in a sorted array of size N.
Def. T(N) = # compares to binary search in a sorted subarray of size <= N. Binary search recurrence. T(N) <= T(N/2) + 1 for N>1, with T(1) = 1
Give an example to show
T(N) <= T(N/2) + 1 for N>1, with T(1) = 1
Show how 1 + 1 + … + 1 become 1 + lg N

3.
Write a program, YI_Better3Sum.java, so its order of growth is N^2 log N

4.
Create a table to compare the execution run time from the original 3-Sum and the Better3Sum.

AOA: Mathematical Models

October 27th, 2015

Screen Shot 2014-10-12 at 11.03.54 PM

Classwork:
Classroom Salon: Video 2.2 Analysis of Algorithms. Mathematical Models. Answer questions, reply to postings, add to posting and vote on answers.
Make sure you have a full set of answers in edmodo.com based on what you learned through the classroom salon discussions on this video.

1. What is defined as Cost of basic operations?
2. What operations would have a constant cost?
3. What operations would have proportional cost?
4. What operations would have N and N^2 cost?
5. what is the frequency of the instructions in the 1-Sum program?
6. How is the frequency of instructions in the 2-Sum different from the 1-Sum?
7. What is the tilde notation?
8. What are the tilde functions for the 2-Sum and the 3-sum?
9. Approximately how many array accesses as a function of input size N for the 3-Sum program?
10. Explain with simplify notation the three examples given for estimating discrete sum.

Homework:
1. Complete work
2. Show mathematically how T(N) is equal to 20.5 seconds when N = 64,000.

Union Find: “is connected to”

October 13th, 2015

PU Book Site
Screen Shot 2014-10-23 at 7.55.21 AM
PU Lectures
Screen Shot 2015-10-13 at 12.54.40 PM
Visit Classroom Salon for videos  1.1, 1.2 and 1.3 and related questions.
Visit edmodo.com to answer the following questions:
1. What are the three assumptions so “is connected to” is an equivalence relation?
2. What are the differences and similarities between the Quick Find and Quick Union operations?

Data Abstractions: Rational numbers

October 8th, 2015

Screen Shot 2014-09-15 at 8.43.34 PM

An immutable data type has the property that the value of an object never changes once constructed.

An assertion is a boolean expression that you are affirming is true at that point in the program.

Use Creative Problem Rational numbers as a template to implement Complex.java as an immutable data type that supports addition, subtraction, and multiplication.

Challenge: implement the division operation.

Homework:
Read more on Asserstions and Inmutability.

 

 

 

 

Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne, Addison-Wesley Professional, 2011, ISBN 0-321-57351-X