3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

48
3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms

Transcript of 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Page 1: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

3rd weekCISC6795, Spring 2011

1

Arrays & Algorithms

Page 2: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Last week

2

Primitive data typesboolean, byte, char, short, int, long, float and doubleArithmetic operations

Control Structures:Sequence execution (by default)Selection statements

Single-selection statement Double-selection statement: can be used to implement multiple-

selection Multiple-selection statement (to introduce later)

Repetition/looping Statements while statement do… while statement for statement

Condition: expression that is either true or false, i.e., any boolean expressionOperators: <, >, ==, !=, >=, <= Boolean operation: &&, ||, ! (negation) (there are more:

&, |, ^ )

Page 3: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

This Week

3

Flow chart representations of algorithm (onboard)Rectangle box represents an activityDiamond represents a decisionArrowed line represents flow

Structured programming Avoid goto statements ! Top-down design, building block

ArrayAlgorithms

Search Sort

Page 4: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Building block idea

4

Draw flow chart for following code segment (nested if … else statement)

if ( studentGrade >= 90 ) System.out.println( "A" );else if ( studentGrade >= 80 ) System.out.println( "B" );else if ( studentGrade >= 70 ) System.out.println( "C" );else if ( studentGrade >= 60 ) System.out.println( "D" );else System.out.println( "F" );

Page 5: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

if…else Double-Selection Statement

Dangling-else problem: Which if does the else associated with ?

if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" );else System.out.println( "x is <= 5" );

Java always associates an else with the immediately preceding if, unless told to do otherwise by braces ({ and }). The compiler actually interprets the statement as

if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" );

5

This is a logic error, as the program is not doing what the programmer intend it to do.

Page 6: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

if…else Double-Selection StatementTo force the nested if…else statement to

execute as it was originally intended:if ( x > 5 ) { if ( y > 5 ) System.out.println( "x and y are > 5" );}else System.out.println( "x is <= 5" );

Braces indicate that the second if is in the body of the first and that the else is associated with the first if.

6

Page 7: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Block StatementTo include several statements in the

body of an if, an else, or a repetition:Enclose the statements in braces, to form a block statement.

A block can be placed anywhere that a single statement can be placed. if ( grade >= 60 )

System.out.println("Passed");else { System.out.println("Failed"); System.out.println("You must take this course again.");}

7

Page 8: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Empty StatementIn if, if …else, while, and for statement, there is no ;

after the condition or the for statement headerif (condition) statementfor (initialization; loopContinuationCondition; increment) statement

Adding ; after condition does not lead to syntax error

Compiler interpret ; as empty statement (recall ; terminates a statement)

A block statement can be placed anywhere a single statement can be placed, so does an empty statement.

8

if (x>0); System.out.println (″x is not greater than 0″);

Page 9: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Demo: Flow Chart

9

Test whether a date given by year, month and day is valid or not.

First step: requirement analysis, what is the required behavior.

To be a valid dateyear must be non-negative month must be between 1 and 12day’s valid range depends on month (and year)

If it’s month 1, 3, 5, 7, 8, 10, 12, day must be between 1 and 31

If it’s month 4, 6, 9, 11, day must be between 1 and 30 If it’s month 2

if it’s a leap year, day must be between 1 and 29 If it’s not a leap year, day must be between 1 and 28

Any of the above condition is false, it’s an invalid date.

Page 10: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Exercise with repetition and flow-chart

10

Draw flow chart for the following task and then implement it in JavaCalculate 210 using a loopCalculate

Test whether a given integer number is a prime number or not

10

3

)54(i

i

Page 11: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

This Week

11

Flow chart representations of algorithm (onboard)Rectangle box represents an activityDiamond represents a decisionArrowed line represents flow

Structured programming Avoid goto statements ! Top-down design, building block

ArrayAlgorithms

Search Sort

Page 12: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Primitive Types vs. Reference TypesJava’s types: primitive types and reference types.Primitive types: boolean, byte, char, short, int, long, float

and double.A primitive-type variable can store exactly one value of

its declared type at a time.reference type variable (sometimes called reference)

stores location of object in memory, i.e., it refer to an object in program.E.g., Scanner input = new Scanner (System.in); A reference is required to invoke (i.e., call) method

defined for the objectE.g., number1 = input.nextInt();

Primitive-type variables do not refer to objects, so such variables cannot be used to invoke methods.

12

Page 13: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

 ArraysAn array is a group of variables (called

elements or components) of the same type.Arrays are objects, so they’re reference types.Elements can be either primitive types or reference

types.To refer to a particular element, specify the

name of the array and position number of the elementThe position number of the element is called the

element’s index or subscript.E.g., c[2]An index can be an expression with a nonnegative

integer.

13

Page 14: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

First element has index zero, and is called zeroth element.Highest index is one less than the number of elements.

14

int [ ] c = new int[ 12 ];

Page 15: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

 Declaring and Creating ArraysTo create an array object, you specify the type

of the array elements and the number of elementsint[] c = new int[ 12 ];Like other objects, arrays are created with keyword

new.Returns a reference that is stored in an array variable,

c. Size of the array can be a variable. A program can declare arrays of any type.

Every element of a primitive-type array contains a value of the array’s declared element type.

Similarly, in an array of a reference type, every element is a reference to an object of the array’s declared element type.

15

Page 16: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

ArraysEvery array object knows its own length

and stores it in a length instance variable.length instance variable of an array is publicit cannot be changed because it’s a final

variable.This is difference from C/C++ !

16

Page 17: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

17

Page 18: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

18

Page 19: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Array InitializerCreate an array and initialize its

elements with an array initializer—a comma-separated list of expressions (called an initializer list) enclosed in braces:Array length is determined by number of

elements in initializer list.int[] n = { 10, 20, 30, 40, 50 };

Compiler counts the number of initializers in the list to determine the size of the array, then sets up the appropriate new operation “behind the scenes.”

19

Page 20: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

20

Page 21: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

21

Page 22: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

22

Page 23: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Examples Using Arrays: Poll AnalysisSummarize the results of data collected in a

survey:Forty students were asked to rate the quality

of the food in the student cafeteria on a scale of 1 to 10 (where 1 means awful and 10 means excellent).

Summarize the results of the poll: count the number of responses of each type (i.e., 1 through 10).

The array responses is a 40-element int array of the survey responses.

11-element array frequency stores the number of occurrences of each response.

23

Page 24: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

24

Page 25: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

25

Page 26: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Bounds CheckingIf the data in the responses array had contained

invalid values, such as 13, the program would have attempted to add 1 to frequency[13], which is outside the bounds of the array.

Java doesn’t allow this.bounds checking: JVM checks array indices to ensure

that they’re greater than or equal to 0 and less than the length of the array,

In case of an invalid index, Java generates an exception to indicate that an error occurred in program at execution time.

We will look at how to catch exception so that the program can recover from error condition

26

Page 27: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Enhanced for StatementIterates through elements of an array without

using a counterAvoiding possibility of “stepping outside” the array.

Syntax:for ( parameter : arrayName )

statementwhere parameter has a type and an identifier, and

arrayName is the array through which to iterate.Parameter type must be consistent with the type of the

elements in the array.Can be used only to obtain array elements — it

cannot be used to modify elements.Can be used in place of the counter-controlled for

statement whenever code looping through an array

27

Page 28: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

28

Page 29: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Using Command-Line ArgumentsIt’s possible to pass arguments from the

command line (these are known as command-line arguments) to an application by including a parameter of type String[] in the parameter list of main.By convention, this parameter is named args.

When an application is executed using java command, i.e., java Cashier weekend Java passes command-line arguments that appear

after class name (i.e., weekend) to the application’s main method as Strings in the array args.

29

Page 30: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

30

Page 31: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

31

Page 32: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

32

Page 33: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

This Week

33

Flow chart representations of algorithm (onboard)Rectangle box represents an activityDiamond represents a decisionArrowed line represents flow

Structured programming Avoid goto statements ! Top-down design, building block

ArrayAlgorithms

Search Sort

Page 34: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Searching Algorithms

34

Problem: determine if an element x is in an array L

We will look at two simple searching algorithmsLinear searchBinary search

Page 35: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Linear Search Algorithm

35

The algorithm below will search for an element x in L and will return “FOUND" if x is in the list and “NOT FOUND" otherwise.

L has n items and L[i ] refers to the i-th element in L.

Linear Search Algorithm1 repeat as i varies from 0 to n-12 if L[i ] = x then return “FOUND" and stop3 return “ FOUND"

Note:Repeat: means do step 2 for i=0, i=1, i=2, …i=n-1We indent line 2 to show that it’s part of the

loop/iterationReturn: means exits the algorithm and returns the

output

Page 36: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Exercise

36

Implement linear search algorithm in JavaUse the template code at here Instrument the code so that it counts the

number of comparisons performed

Page 37: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Efficiency of Linear Search Algorithm

37

If x appears once in L, on average how many comparisons (line 2) would the algorithm to make on average?On average n/2 comparisons

If x does not appear in L, how many comparisons would the algorithm make?n comparisons

Would such an algorithm be useful for finding someone in a large (unsorted) phone book?No, it would require scanning through entire

phone book!Need a better way!

Page 38: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Binary Search Algorithm Overview

38

Binary search algorithm assumes that L is sortedAscending order or descending order

This algorithm need not examine each element, it maintains a “window" in which element x may residewindow is defined by indices min and max which specify

the leftmost and rightmost boundaries in LIn the beginning, x can be anyway in L, i.e., min=0, max=n-

1At each iteration of the algorithm, the window is cut in halfRemember number guessing game ?I am thinking about the number between 1 and 100, you guess it by

asking question such as “Is the number larger than 30”?

Page 39: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Binary Search Algorithm

39

Binary Search Algorithm assuming L has been sorted in ascending order1 set min to 0 and set max to n-12 Repeat until min > max3 Set midpoint to (min + max)/24 Compare x to L[midpoint], three possible

results: (a) if x = L[midpoint] then return “FOUND" (b) if x > L[midpoint] then set min to (midpoint + 1) (c) if x < L[midpoint] then set max to (midpoint -1)

5 return “FOUND"Note: the repeat loop spans lines 2-4.

Page 40: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Exercise:

40

Implement the binary search algorithm in Java

Can you modify the algorithm to work for L sorted in descending order?

Page 41: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Binary Search Example

41

Use binary search to find element “4" in sorted list (1 3 4 5 6 7 8 9). List values of min, max and midpoint after each iteration of step 4. How many values are compared to “4"?1 Min = 1 and max = 8 and midpoint = 1/2 (1 + 8) = 4 (round

down). Since L[4] = 5 and since 4 < 5 we execute step 4c and max = midpoint - 1 = 3.

2 Now min = 1, max = 3 and midpoint = 1/2 (1 + 3) = 2. Since L[2] = 3 and 4 > 3, we execute step 4b and min = midpoint + 1 = 3.

3 Now min = 3, max = 3 and midpoint = 1/2 (3 + 3) = 3. Since L[3] = 4 and 4 = 4, we execute step 4a and return “FOUND.“

we check three values: 3, 4, and 5. Since we cut the window in half each iteration, it will

shrink very quickly (about log2 n comparisons).

Page 42: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Comparison of Linear and Binary Search

42

Best case performance1 comparison for both algorithms

worst case performancelinear search carries out n comparisonsbinary search carries out about log2 n comparisons

Binary search is much more efficientIf n = 1K we have 1024 vs. 10 comparisonsIf n = 1M we have ~1, 000,000 vs. 100 comparisonsIf n = 1G we have ~1,000,000, 000 vs 1000

comparisonsDrawback of binary search: requires sorting, and

this requires a decent amount of workBut sorting only has to be done once and this will be

worthwhile if we need to search the list many times

Page 43: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Sorting Algorithms

43

Sorting algorithms are one of the most heavily studied topics in Computer ScienceSorting is critical to improve searching efficiency

There are many well known sorting algorithms in Computer Science, we focus on two:BubbleSort: a very simple but inefficient

sorting algorithmMergeSort: a slightly more complex but

efficient sorting algorithm

Page 44: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

BubbleSort Algorithm Overview

44

BubbleSort: repeatedly scan the list, in each iteration “bubbles" the largest element in the unsorted part of the list to the end After 1 iteration, largest element in last positionAfter 2 iterations, largest element in last position

and second largest element in second to last position

….requires n-1 iterations

at (n-1)-th iteration, only one item left, must already be in proper position (i.e., the smallest must be in the leftmost position)

Page 45: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

BubbleSort Algorithm

45

Input: n-element array L Bublesort Algorithm

1 Repeat as i varies from n-1 down to 12 Repeat as j varies from 0 to i – 13 If lj > lj+1 swap lj with lj+1

Outer loop (1-3): i controls which part of the array is scanned for each iteration. (Only unsorted part is checked.)

In 1st iteration, check everything, l0, l1, … ln-2 In 2nd iteration, check everything except last

element, l0, l1, …, ln-3 …

Inner loop (2-3): bubble up largest element in unsorted part of list to the end

Page 46: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

BubbleSort Example

46

Use BubbleSort to sort list of number (9 2 8 4 1 3) into increasing order.

How many comparisons did you do each iteration? Can you find a pattern?

Page 47: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

 Preview: Collections and Class ArrayList Class Arrays provides static methods for common array

manipulationsSort, binarySearch, equals , fill

Collections provide efficient methods that organize, store and retrieve your data without requiring knowledge of how the data is being stored.

The collection class ArrayList<T> (from package java.util) can dynamically change its size to accommodate more elements.

The T is a placeholder—when declaring a new ArrayList, replace it with the type of elements that you want the ArrayList to hold.

This is similar to specifying the type when declaring an array, except that only nonprimitive types can be used with these collection classes.

Classes with this kind of placeholder that can be used with any type are called generic classes.

Figure 6.17 shows some common methods of class ArrayList<T>. Lines 20–21 display the items in the ArrayList.

47

Page 48: 3 rd week CISC6795, Spring 2011 1 Arrays & Algorithms.

Summary

48