1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

The University of Adelaide, School of Computer Science
Programming and Data Structure
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
1 Various Methods of Populating Arrays Randomly generated integers.
CS 106 Introduction to Computer Science I 02 / 29 / 2008 Instructor: Michael Eckmann.
Arrays part 2 Applications & such. Returning an array from a method A method can return an array, just like it can return any other kind of variable;
Cmput Lecture 8 Department of Computing Science University of Alberta ©Duane Szafron 2000 Revised 1/26/00 The Java Memory Model.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Searching and Sorting Linear Search Binary Search Selection Sort
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Java: How to Program Arrays and ArrayLists Summary Yingcai Xiao.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 2D Arrays, Sorting Lecture 23, Fri Mar
Unit 271 Searching and Sorting Linear Search Binary Search Selection Sort Insertion Sort Bubble (or Exchange) Sort Exercises.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Lists in Python.
1 Chapter 7 Single-Dimensional Arrays. 2 Arrays Array is a data structure that represents a collection of the same types of data elements. A single-dimensional.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
1 Chapter 4: Arrays and strings Taufik Djatna
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
Array Processing - 2. Objectives Demonstrate a swap. Demonstrate a linear search of an unsorted array Demonstrate how to search an array for a high value.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
More arrays Primitive vs. reference parameters. Arrays as parameters to functions.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Computer Science 210 Computer Organization Arrays.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Arrays Pepper. What is an Array A box that holds many of the exact same type in mini-boxes A number points to the mini-box The number starts at 0 String.
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
Pointers OVERVIEW.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
Types in Java 8 Primitive Types –byte, short, int, long –float, double –boolean –Char Also some Object types: e.g. “String” But only single items. What.
Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Arrays. 2 Till now we are able to declare and initialize few variables Reality: need to compute on a large amount of data Arrays are data structures that.
Sorting an array bubble and selection sorts. Sorting An arrangement or permutation of data An arrangement or permutation of data May be either: May be.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
1 BUILDING JAVA PROGRAMS CHAPTER 7.2 ARRAY TRAVERSAL ALGORITHMS.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Introducing Arrays. Too Many Variables?  Remember, a variable is a data structure that can hold a single value at any given time.  What if I want to.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Arrays Chapter 7.
Searching and Sorting Searching algorithms with simple arrays
Java Arrays. Array Object An array :a container object holds a fixed number of values of a single type. The length of an array is established when the.
Building Java Programs
CS2011 Introduction to Programming I Arrays (II)
CSE 373 Data Structures and Algorithms
Building Java Programs
Lecture 03 & 04 Method and Arrays Jaeki Song.
Presentation transcript:

1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method. – Modifying a value in a method does not have any effect on the caller – But if the value is a reference then the change affects ‘what is referred to’ and so all references will see the change. References are addresses and hence a modification of the contents at the address will have “global” visibility On the other hand non-referential argument values are just copied in the “local memory” of a method; so a modification to a value within a method always remains local (changes contents only of local memory)

2

3

The Sorting Problem Let S be a sequence of entities which can be ordered (that is for any 2 elements, say a, b in the sequence exactly one of the following is true a b or a=b). Sort(S) : arranges the sequence in ascending or descending order.

Sort algorithms The sorting problem is one of the best studied problems and many algorithms exist. It is also practically important – sorting is routinely required in almost all database centred applications.

Selection sort: example //green is min, | is separator // after first round, blue sorted //stop since only one left

Selection sort algorithm //S is the array to be sorted. sepIndex=0; loop (s.length-1) times { minI=findMinIndex(S,sepIndex); exchange(S,sepIndex,minI); sepIndex++; }

Selection sort - findMinIndex int findMinIndex(int[]S,int from) { int minI=from; for(int i=from+1;index<S.length;i++) { if (S[i]<S[minI]) minI=i; } return minI; }

Bubble sort: example //sort ascending, | is unsorted-sorted separator //interchange neighbours from 0 till end //after first pass //after second pass //after third pass //4th pass, no interchange Stop condition: no interchange or | is at start.

Bubble sort algorithm lim=S.length-1; while (bubblePass(S,lim) && lim>0) { lim--; }

Bubble sort - bubblePass boolean bubblePass(int [] s, int to) {boolean interchange=false; for(int i=0; i<to; i++) { if (S[i]>S[i+1]){ //exchange contents of S[i],S[i+1] interchange=true; } return interchange; }

Mergesort msort(s) { /* Split S into two (almost) equal parts s1,s2*/ split(s,s1,s2); msort(s1); msort(s2); /* at this point s1, s2 are sorted */ merge(s1,s2,ss); return ss; }

Merge merge(s1, s2, s) { s=initialize to s1.length+s2.length i1=0;i2=0,i=0; while(i1<s1.length && i2<s2.length){ if(s1[i1]<s2[i2])s[i]=s1[i1++]; else s[i]=s2[i2++]; i++ } // Now copy rest of s1 or s2 to s return s;}

14 Finding average class Average { public static void main (String arg[]) { double dailyRainFall[] = {12.3, 13.5, 4.2, 2.4, 1.1, 0, 10.8}; int i; double average = 0; for (i=0; i<7; i++) { average += dailyRainFall[i]; } average /= 7; System.out.println (“Average rain fall: ” + average + “ mm”); }

15 Finding maximum class Maximum { public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; Initialize (numbers, n); System.out.println (“Maximum: ” + FindMax (numbers, n)); }

16 Finding maximum public static void Initialize (double numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) + Math.cos(2*Math.PI/(i+2)); }

Finding maximum public static double FindMax (double numbers[], int length) { double max = numbers[0]; int i; for (i=1; i<length; i++) { if (numbers[i] > max) { max = numbers[i]; } return max; } } // end class

Finding maximum Want to print the position of the maximum also –Need to return two values from FindMax –Use a 2-element array as return type –Shows why returning local reference does not work –Shows the distinction between two different memory areas: stack and heap

Finding max and max index class Maximum { public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[]; Initialize (numbers, n); result = FindMax (numbers, n); // Danger! System.out.println ("Maximum: " + result[0] + ", Position: " + (int)result[1]); }

Finding max and max index public static void Initialize (double numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) + Math.cos(2*Math.PI/(i+2)); }

Finding max and max index public static double[] FindMax (double numbers[], int length) { // Does not work double result[] = {numbers[0], 0}; int i; for (i=1; i<length; i++) { if (numbers[i] > result[0]) { result[0] = numbers[i]; result[1] = i; } return result; // Local reference on stack } } // end class

Finding max and max index public static double[] FindMax (double numbers[], int length) { // This one works double result[] = new double[2]; // On heap result[0] = numbers[0]; result[1] = 0; int i; for (i=1; i<length; i++) { if (numbers[i] > result[0]) { result[0] = numbers[i]; result[1] = i; } return result; // Reference on heap } } // end class

Array layout in memory Recall that every variable requires some space to be stored in memory –Often the compiler is responsible for allocating this space –In other words, every variable has an address (just like you and I have addresses) –The address is often called a reference of a variable in Java –If I try to print the value at this address, I will get the value of the variable How is an array stored in memory?

Array layout in memory The array elements are stored contiguously in memory –numbers[0], numbers[1], … –Starting address is numbers (same as the address of numbers[0]), add 8 to get the address of numbers[1] –doubles are 64 bits in size and memory is always byte addressed (one byte is 8 bits) –Putting array names in method arguments is equivalent to passing the arrays by reference: modifications to arrays inside the method are reflected outside the method –Of course, it is possible to pass individual array elements (not by reference, but by value i.e. as private copies)

FindMax: reference as a value class Maximum { // Still pass by value public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[] = new double[2]; Initialize (numbers, n); result[0] = numbers[0]; result[1] = 0; FindMax (numbers, n, result); // reference System.out.println ("Maximum: " + result[0] + ", Position: " + (int)result[1]); }

FindMax: reference as a value public static void Initialize (double numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) + Math.cos(2*Math.PI/(i+2)); }

FindMax: reference as a value public static void FindMax (double numbers[], int length, double r[]) { int i; for (i=1; i<length; i++) { if (numbers[i] > r[0]) { r[0] = numbers[i]; r[1] = i; } } // end class

FindMax: passing values class Maximum { // This example does not work public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[] = new double[2]; Initialize (numbers, n); result[0] = numbers[0]; result[1] = 0; FindMax (numbers, n, result[0], result[1]); System.out.println ("Maximum: " + result[0] + ", Position: " + (int)result[1]); }

FindMax: passing values public static void Initialize (double numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) + Math.cos(2*Math.PI/(i+2)); }

FindMax: passing values public static void FindMax (double numbers[], int length, double max, double position) { int i; for (i=1; i<length; i++) { if (numbers[i] > max) { max = numbers[i]; position = i; } } // end class

Always pass by value Java always passes arguments by value –References are just a special kind of values –Modifying a value in a method does not have any effect on the caller –Modifying a value pointed to by a reference in a method does change the value in the caller also References are addresses and hence a modification of the contents at the address will have “global” visibility On the other hand, argument values are just copied in the “local memory” of a method; so a modification to a value within a method always remains local (changes contents of local memory)

Reversing an array class Reverse { public static void main (String arg[]) { int size = 10; int somethingStrange[] = new int[size]; Initialize (somethingStrange, size); PrintArray (somethingStrange, size); Reverse (somethingStrange, size); PrintArray (somethingStrange, size); }

Reversing an array public static void Initialize (int array[], int size) { int i; array[0] = 1; for (i=1; i<size; i++) { array[i] = (array[i-1]*3) % 23; }

Reversing an array public static void Reverse (int array[], int size) { int head = 0, tail = size-1; while (head < tail) { Swap (array, head, tail); head++; tail--; }