Transcript .ppt

Announcements
•
•
•
•
P3 due tomorrow
P4 handed out today -- Sorting and Matlab
Prelim leftovers -- pick them up after class
Grades will be done on a curve
CS 100
Lecture 14
1
Today’s Topics
• Quick review of recursive quicksort
• Quick look at iterative quicksort
• Matlab introduction
CS 100
Lecture 14
2
Review of quicksort
• Given an array b[0..k]
– if b.length = 1, done
– if b.length = 2, then swap if necessary, done.
– partition the array around b[0], suppose value in
b[0] ends up in position j
– quicksort b[0..j-1]
– quicksort b[j+1..k]
• This version of quicksort is recursive (calls
itself)
CS 100
Lecture 14
3
Iterative quicksort (no recursion)
• After partitioning the array, it looks like:
h
b <= x
j
x
k
>x
• There are now two sections to sort, b[h..j-1] and
b[j+1..k], and while one is being sorted, it must be
remembered to sort the other.
• Sorting b[h..j-1] will result in partitioning and the
creation of two other sections to sort; these must also
be “remembered”.
CS 100
Lecture 14
4
Create a class Bounds
// An instance represents the bound f and l of an
// array section b[f..l] (for some array)
public class Bounds {
public int f;
public int l;
// Constructor: instance with f=fp and l=lp
public Bounds(int fp, int lp)
{f= fp; l= lp;}
}
CS 100
Lecture 14
5
public void Quicksort(int [ ] b, int h, int k) {
Bounds c [ ] = new Bounds [ k+1-h];
System.out.println(k);
System.out.println(h);
c[0]= new Bounds(h,k);
int i= 1;
// inv: b[h..k] is sorted iff all its subsegments
// defined by elements of c[0..i-1] are sorted
while (i > 0) {
i = i -1;
int f= c[i].f; int l= c[i].l;
// Process segment b[f..l]
CS 100
Lecture 14
6
if (l-f==1) {// b[f..l] has two elements
if (b[f] > b[l]) {
// Swap b[f] and b[l]
int t= b[f]; b[f]= b[l]; b[l]= t; }}
else if (l-f>1) { //b[f..l] has > 2 elements
// Add bounds of b[f..j-1] and b[j+1..k] to c
int j= partition(b,f,l);
c[i]= new Bounds(f,j-1);
i= i+1;
c[i]= new Bounds(j+1,l);
i= i+1;}}}
CS 100
Lecture 14
7
Size of array c
How big can array c get? Let b[h..k] have n values, and let
b be already sorted. At each step, b[f..j-1] would be
empty and b[j+1..k]would have all but one of the
elements. After 3 loop iterations, we would have
c[0] represents a segment of 0 elements
c[1] represents a segment of 0 elements
c[2] represents a segment of 0 elements
c[3] represents a segment of n-3 elements
In worst case array c needs almost n array elements!
CS 100
Lecture 14
8
How to fix this. . .
Put largest of the two segments b[f..j-1], b[j+1..k] on c
first, then the smaller. Then, we can show that that if
c[0] represents a segment of m elements, c looks like
c[0] represents m elements
c[1] represents < m/2 elements
c[2] represents < m/4 elements
c[3] represents < m/8 elements
…
c[i-1] represents m/ 2 i-1 elements
c has at most 1+ log m elements
So c has at most 1 + log n elements. Much better!
CS 100
Lecture 14
9
Changes to algorithm
• Changes to ensure that array c never gets
bigger than log (l-f). If the array has 250 elements,
array c need have no more than 50 elements.
1. Change allocation of c to
Bounds c [ ] = new Bounds [ 50];
2. Change implementation of “Add bounds …” to
the following:
CS 100
Lecture 14
10
Code Modifications
// Add bounds of b[f..j-1] and b[j+1..k] to c
// --put larger segment on first
if (j-f > l-j) {
c[i]= new Bounds (f,j-1); i= i+1;
c[i+1]= new Bounds(j+1..k); i= i+1;
}
else {
c[i]= new Bounds (j+1..k); i= i+1;
c[i]= new Bounds(f,j-1); i= i+1;
}}
CS 100
Lecture 14
11
Recursive vs. Iterative
•
•
•
•
Which do you like better?
Which is easier to understand?
In P4, implement whichever you like
Choose better variable names that what
you’ve seen in class
• More on recursion later. . .
CS 100
Lecture 14
12
Matlab Matlab Matlab
• Yet another programming language
• Think of it as a graphical calculator arrays
and scalars
• Pratap’s Getting Started with Matlab is on
reserve in the Engineering library
• Matlab is also available in Carpenter and
Upson labs -- ask consultants how to access
it
CS 100
Lecture 14
13
Why Matlab?
• The premier package for numerical computing, particularly
arrays (matrices). Widely used in science/engineering.
• Provides high-level interface to best-of-class numerical
methods. Problem-solving without lower-level
programming details.
• Powerful graphics and visualization tools.
– has variables, loops, conditionals, functions
– but much array/matrix computation can be done
directly without loops.
CS 100
Lecture 14
14
The Matlab environment
• Enter expressions or commands in the console window.
Commands are executed immediately. An expression is evaluated
and its value is immediately displayed.
• Can define command scripts and new functions (future lecture).
• Most important feature: help command. Type help to get a
general list of available topics, or help topic for information on
topic.
• Type more on
in the console window to pause output after each full screen. Hit
space to continue.
• Anything following a % is ignored. Use it to include notes or
comments in a session.
• To leave Matlab, type
CS 100
quit
Lecture 14
15
Some expressions and operators
• The usual basic arithmetic operations are provided (+, –, *, /, and
^). Everything is floating-point, although integer values are
displayed without a fractional part.
– 9/10 is 0.9 in Matlab
– ^ is exponentiation (2 ^ 10)
• Logical operations treat 1 as the value true and 0 as false.
• Comparisons: <, <=, ==, ~=, >=, >
• Logical Operators: &, |, ~
• Examples:
3*4+5
3*4+5/2
3 * (4 + 5) / 2
(3 < 2 ^ 2) & ~ (3 < 2)
(3 < 2 ^ 2) | ~ (3 < 2)
CS 100
Lecture 14
16
Variables
• Variables are created when they are first assigned a value.
x = 17
y=3*x
• All variables are global (for now).
• A variable exists from the time it is created until you quit Matlab.
• Variable names are case-sensitive. Entering
a = 17
A = 42
creates two separate variables.
• Several variables containing useful constants are already defined
pi
3.14159…
Inf
i, j
sqrt(–1)
CS 100
Lecture 14
17
NaN 0/0
Functions
• Matlab provides a rich collections of
standard functions.
– Trigonometry: sin, cos, tan, cot, asin,
acos, atan, atan2…
– Exponential: exp, log, log10, sqrt
– Complex: real, imag, abs, …
– Rounding: floor, ceil, round, rem, sign
– Specialized: bessel, gamma, erf, log2, rat,
…
CS 100
Lecture 14
18
Examples of function use
x = 3;
y = 4;
d = sqrt(x ^ 2 + y ^ 2)
sin(pi / 2)
exp(1)
sqrt(–1)
CS 100
Lecture 14
19
Input and Output in Matlab
• The value of a Matlab expression or statement is displayed
immediately unless it is followed by a semicolon.
z=x^2
w = x ^ 3;
• To change the precision of the output type
format long
format short
Other formats are also available. (Enter help format for details.)
• You can edit and reenter previous console input. Use the up- and
down-arrow keys to access previous entries.
CS 100
Lecture 14
20
Sample console window
CS 100
>> z = 1;
>> x = 3; y = 4;
>> d = sqrt(x^2 + y^2)
d=
5
>> x = exp(1)
x=
2.7183
>> y = sin(p1/2)
??? Undefined function or variable 'p1'.
>> y = sin(pi/2)
y=
1
Lecture 14
21
Arrays in Matlab
• All data in Matlab is actually an array — a 1- or 2dimensional table of numbers. (We only consider 1-D
arrays in this lecture.)
• A single value, called a scalar, is simply an array of size
1.
• To construct a 1-D array, list its elements surrounded by
square brackets.
y = [4 -5 10 0 5.2]
x = [–5 sqrt(2) 17 2^3]
>> a = [4, z, x, y]
a=
4.0000
CS 100
1.0000
2.7183
Lecture 14
1.0000
22
More basics of Matlab arrays
• Individual elements are accessed using a
parenthesized subscript.
x(3)
• The first element of array x is x(1).
• Can assign to elements of array as in Java.
y(1) = 0
• The number of elements in array x is given
by the built-in function length(x)
CS 100
Lecture 14
23
Array functions
• An array of evenly-spaced values can be generated by
linspace(minVal, maxVal, nVals)
Example: array of 100 values spaced from 0 to 2.
v = linspace(0, 2*pi, 100);
• There are many functions to compute facts about arrays.
min(x)
max(x)
mean(x)
sum(x)
x(1) + … +x(length(x))
prod(x)
x(1) * … * x(length(x))
CS 100
Lecture 14
24
Examples of previous
>> a = linspace(0, 10, 5)
a=
0 2.5000 5.0000
>> min(a)
ans =
0
>> max (a)
ans =
10
>> sum(a)
ans =
25
CS 100
7.5000 10.0000
>> prod(a)
ans =
0
>> mean(a)
ans =
5
Lecture 14
25
Creating arrays
• Two arrays can be combined with a comma and brackets:
x = [1 2 3];
y = [4 5 6];
[x, y]
(is [1 2 3 4 5 6])
z = [x, [x, y]];
• The colon can be used to generate a sequence of values.
Forms:
lowValue : highValue
lowValue : step : highValue
CS 100
Lecture 14
26
Examples of colon use
1 : 10 (yields 1 2 3 4 5 6 7 8 9 10)
1 : 2 : 10 (yields 1 3 5 7 9)
1 : 0.5 : 10 (yields 1 1.5 2 2.5 . . . 9 9.5 10)
10 : –1 : 1 (yields 10 9 8 7 . . . 1)
0 : 0.01 : 0.5
• A sequence of values is an array value.
a = 0 : 2 : 16
b = [1 : 6] / 3 (yields b = 0.3333 0.6667 1.0000 1.3333
1.6667 2.0000
• A sequence of integers can also be used to select a segment of an
array.
a(3:6)
Remember: arrays in Matlab start at 1 (in Java at 0)
CS 100
Lecture 14
27