330 likes | 406 Views
Lec.5 Arrays:. Jiang (Jen) ZHENG May 23 th , 2005. Outline. Quick Review Static/Class/Predefined Methods In Two Page Call By Value Variable scope Recursion Array Introduction to Array Java Array. Static Methods In Two Pages. static method / class method / predefined method
E N D
Lec.5Arrays: Jiang (Jen) ZHENG May 23th, 2005
Outline • Quick Review • Static/Class/Predefined Methods In Two Page • Call By Value • Variable scope • Recursion • Array • Introduction to Array • Java Array CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Static Methods In Two Pages • static method / class method / predefined method • General Form: • public static ReturnType Identifier (ParameterList) block • For Ex: public static double square ( double x) { double result; // Variable Declaration result = x*x; // statements return result; // return statement: can return a value or return a // value of an expression. Ex: return x*x; } • Return Type • the type of the value returned • Or void if nothing returned. CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Static Methods In Two Pages • Parameter List • 0 or more parameters passed to the method • Each parameter: type identifier • Place holder for actual values. • public keyword is optional. Exception: main() • These are often called in the following way: ClassName.methodName(param_list) Ex. Math.sqrt(x); • Some are also called in the following way ClassName.ObjectName.methodName(param_list) Ex: System.out.println(“Hello There”); CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Call By Value • Parameters in Java are passed by value • The parameter is a copy of the evaluation of the argument • Any changes to the parameter do not affect the argument • Arguments passed into a method cannot be changed within the method, either intentionally or accidentally CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Local variables and scope • Variables declared within a method are local to that method • They exist only within the context of the method • This includes parameters as well • We say the scope of these variables is point in the method that they are declared up to the end of the method • However, Java variables can also be declared within blocks inside of methods • In this case the scope is the point of the declaration until the end of that block • Note that either way, these variables cannot be shared across methods CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Recursion • Three important rules for any recursive algorithm: • There must be some recursive case, in which the algorithm “calls itself” • There must be some base case, in which no recursive call is made • The recursive calls must lead eventually to the base case • Usually by “reducing” the problem size in some way CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Recursion • Think about the Lab 2 using recursive function? • Recursive Case: • F (n) = F(n-1) + F(n-2) • Base Case: • F(1) = F(0) = 1 • The Recursive case will lead to base case • Final Code: • public static int Fibonacci ( int index) { if ( index == 0 || Index == 1) return 1; else return Fibonacci (index -1) + Fibonacci (index -2); } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Arrays • So far we have stored data in a 1:1 fashion • 1 variable : 1 value • This works fine if we know exactly how many values we will need to store, and if there are few of them • However, consider the following scenario: • We want to input the test scores of a given number of students, then 1) find the maximum, 2) minimum, 3) average and 4) list them in sorted order CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Arrays • We can do the first three things using only a few variables • Read in current score • Add it to the sum • If it is less than the minimum score, make it the minimum score • If it is greater than the maximum score, make it the maximum score • Repeat until all scores have been read • Divide sum by number of scores to get average • However, what about listing them in sorted order? CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Arrays • We can’t know the final order until all scores have been read • Last value could be smallest, largest or anywhere in between • Thus, we need to store all of the values as they are being read in, THEN sort them and print them out • To do this we need a good way to store an arbitrary number of values, without requiring the same number of variables • This is a good example of where an array is necessary CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Java Arrays • Java Arrays • In Java, arrays are objects, with certain properties • For now, we will not focus on this, but will look at it more later • Simply put, an array is logically a single variable name that allows access to multiple variable locations • In Java, the locations also must be contiguous and homogeneous • Each directly follows the previous in memory • All values stored are of the same type CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Java Arrays • Syntax: • For now, consider only PRIMITIVE TYPES • We create a Java array in 2 steps: 1.prim_type [] var_name; • where prim_type is any primitive type • where var_name is any legal identifier • This creates an array variable, but NOT an actual array 2.var_name = new prim_type[arr_size] • where arr_size is the number of elements that will be in the array • Indexing in Java always starts at 0 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Java Arrays • Ex: int [] myArray; myArray = new int[20]; // size can be a variable // or expression • These two steps can be done as one if we’d like int [] myArray = new int[20]; • Once we have created the array, we now need to put values into it • Numeric types are initialized to 0 • Booleans are initialized to false • We can change these values via indexing CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Java Arrays • Indexing an array • An array variable gives us access to the “beginning” of the array • To access an individual location in the array, we need to index, using the [] operator • Ex: myArray[5] = 250; myArray[10] = 2 * myArray[5]; myArray[11] = myArray[10] – 1; • Show on board CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Java Arrays • Iterating through an array • We can easily iterate through an entire array using a loop (often a for loop) • To know “when to stop” we access the length attribute of the array variable • Note the syntax for (int i = 0; i < myArray.length; i++) { System.out.print(“Value ” + i “ = ” + myArray[i]); } CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Direct Access and Sequential Access • The previous two slides demonstrate the two basic ways of accessing arrays: • Direct Access • Arbitrary items are accessed by providing the appropriate index of the item • Sequential Access • Items are accessed in index order from beginning to end (or from end to beginning) • The usefulness of arrays comes from allowing access in both of these ways CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
References and Reference Types • Java has primitive types and reference types • Recall how they are stored • With primitive types, data values are stored directly in the memory location associated with a variable • With reference types, values are references to objects that are stored elsewhere in memory var1 100 s s Hello There! CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
References and Reference Types • What do we mean by “references”? • The data stored in a variable is just the “address” of the location where the object is stored • Thus it is separate from the object itself • Ex: If I have a Contacts file on my PC, it will have the address of my friend, Joe Schmoe (stored as Schmoe, J.) • I can use that address to send something to Joe or to go visit him if I would like • However, if I change that address in my Contacts file, it does NOT in any way affect Joe, but now I no longer know where Joe is located • However, I can indirectly change the data in the object through the reference • Knowing his address, I can go to Joe’s house and steal his plasma TV CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
A B Reference Types • This is how arrays are handled in Java • The array variable is a reference to the actual array • If I assign the variable (as a whole) it does not change the array object • But I can alter the contents of the array through indexing • Ex: int [] A = new int[5]; for (int i = 0; i < 5; i++) A[i] = 2*i; int [] B = A; A[3] = 5; A = new int[4]; A[1] = 3; A[3] = 7; 5 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Arrays as Parameters • Recall that all Java parameters are value • A copy of the argument is passed to the parameter • Changes to the parameter do not affect the argument • What about arrays? • Still passed by value, but now what is copied is the reference (i.e. the variable), NOT the object • Thus the effect is that the parameter is another reference to the same object that the argument is a reference to • We cannot change the argument variable in the method but we CAN change the array object! CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Arrays as Parameters • Sounds confusing, right? • Not so much once you picture it! • Show example on board • We will also see an example shortly with ex7.java • This allows us to change arrays within methods • Ex: Read data into an array • Ex: Remove data from an array • Ex: Sort an array CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Searching an Array • Often we may want to see if a value is stored in an array or not: • “Is this book in the library?” • “Is Joe Schmoe registered for classes?” • There are many searching algorithms available, some simple and some quite sophisticated • We will start off simple here with Sequential Search CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Sequential Search • Sequential Search • Start at the beginning of the array and check each item in sequence until the end of the array is reached or the item is found • Note that we have two conditions here • One stops the loop with failure (get to end) • The other stops the loop with success (found item) • We should always consider all possible outcomes when developing algorithms • Q: What kind of loop is best for this? • Think about what needs to be done • Let’s look at an example: ex7.java CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Simple Sorting • What does it mean to sort our data? • Consider an array, A of N items: A[0], A[1], A[2], …, A[N-1] • A is sorted in ascending order if A[i] < A[j] for all i < j • A is sorted in descending order if A[i] > A[j] for all i < j • Q: What if we want non-decreasing or non-increasing order? • What does it mean and how do we change the definitions? CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Simple Sorting • How do we sort? • There are MANY ways of sorting data • Sorting has been widely studied in computer science • Some algorithms are better than others • The most useful measure of “better” here is how long it takes to run • The better algorithms run a lot more quickly than the poorer algorithms • However, some very simple algorithms are ok if N is not too large • We will look at a simple algorithm here CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
SelectionSort • SelectionSort is very intuitive: • Idea: Find the smallest item and swap it into index 0 Find the next smallest item and swap it into index 1 Find the next smallest item and swap it into index 2 … Find the next smallest item and swap it into index N-2 • What about index N-1? • Let’s trace it on the board for the following data: CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
SelectionSort • Let’s look at the code • SelectionSort.java – (online on the CS401 Web site) • Note: • Done in a modular way utilizing methods • Trace it on the example from previous slide • See result on board • In CS 0445 you will see other, better ways of sorting CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Binary Search • Consider Sequential Search again • Note that in the worst case we look at every item in the array • We say this is a linear run-time– or time proportional to N, the number of items in the array • Can we do better? • If the data is unsorted, no • It could be any item, so in the worst case we’ll have to try them all • What if we sort the data? Will that help? CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Binary Search • Idea of Binary Search: • Searching for a given key, K • Guess middle item, A[mid] in array • If A[mid] == K, we found it and are done • If A[mid] < K then K must be on right side of the array • If A[mid] > K then K must be on left side of the array • Either way, we eliminate ~1/2 of the remaining items with one guess • Show on board for a search for 40 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Binary Search • What if item is not in array? We need a stopping condition in the “not found” case • Think about what is happening with each test • Either we move left index to the right or • We move right index to the left • Eventually they will “cross”– in this case the item is not found • Idea is there is “nothing left” in the array to search • Search previous array for 25 • How to code this? Not difficult! • See BinarySearch.java CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Binary Search • So is Binary Search really an improvement over Sequential Search • Each “guess” removes ~½ of the remaining items • Thus the total number of guesses cannot exceed the number of times we can cut the array in half until we reach 0 items • Ex: 32 16 8 4 2 1 => 6 • Generally speaking, for N items in the array, in the worst case we will do ~log2N guesses • This is MUCH better than Sequential Search, which has ~N guesses in the worst case • You will discuss this more in CS 0445 and CS 1501 CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5
Topics for next lecture • Reading Assignment: Chapter 5.9-5.12 Chapter 6.1-6.4 You don’t need to know the details but you should know what are those when I talk about it. CS401/COE401 Summer 2005.Department of Computer Science.University of Pittsburgh.Lecture 5