1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri

Slides:



Advertisements
Similar presentations
Garfield AP Computer Science
Advertisements

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,
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Written by: Dr. JJ Shepherd
CSE 373: Data Structures and Algorithms
1 Selection Sort and Quick Sort Instructor: Mainak Chaudhuri
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
1 Graphs and Search Trees Instructor: Mainak Chaudhuri
C Static Arrays Pepper. What is an array? Memory locations – same type – next to each other (contiguous) – Same name – Indexed by position number of type.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
1 Linear and Binary Search Instructor: Mainak Chaudhuri
Solving Recurrence Relations T(n)= 2T(n/2)+n = 2*(2T(n/4)+n/2)+n = 4*T(n/4) +2*n = 8*T(n/8) + 3*n = 2 (log n) * T(1) + (log n) * n = n * 1 + n log n O(n.
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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
Pointers OVERVIEW.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
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.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
CSci 125 Lecture 21 Martin van Bommel. Memory Allocation Variable declarations cause compiler to reserve memory to hold values - allocation Global variables.
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.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
Pointers *, &, array similarities, functions, sizeof.
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.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
1 Insertion sort [ ] i=1 j=1 i=2 j=2 insert i=3 at j=1 [ ] i=3 j=1 insert i=4 at j=0 [
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
1 BUILDING JAVA PROGRAMS CHAPTER 7.2 ARRAY TRAVERSAL ALGORITHMS.
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.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
Review Quick Sort Quick Sort Algorithm Time Complexity Examples
1 Examples of class: Recursive data structures Instructor: Mainak Chaudhuri
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
Arrays What is an array… –A data structure that holds a set of homogenous elements (of the same type) –Associate a set of numbers with a single variable.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
Computer Organization and Design Pointers, Arrays and Strings in C
Week 13: Searching and Sorting
Recitation 13 Searching and Sorting.
Announcements Project checkpoint next week after lab sessions
CSCE 210 Data Structures and Algorithms
Defining methods and more arrays
Chapter 16 Pointers and Arrays
Merging two sorted arrays
CSE 373 Data Structures and Algorithms
Data Structures & Algorithms
Presentation transcript:

1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri

2 Arrays 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 can hold a series of values –Just a new name for matrix –Just like a matrix index, an array uses an index to access a particular value

3 Initializing an array int justAVector[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; String myFriendsNames[] = {“John”, “Brian”, “Jill”, “Jack”, “Ivan”}; char firstFewDigits[] = {‘0’, ‘1’, ‘2’, ‘3’}; boolean whichOfMyFriendsAreTall[] = {false, false, true, true, false}; Size of an array array_name.length

4 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; float average = 0; for (i=0; i<7; i++) { average += dailyRainFall[i]; } average /= 7; System.out.println (“Average rain fall: ” + average + “ mm”); }

5 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)); }

6 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)); }

7 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

8 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

9 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]); }

10 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)); }

11 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

12 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

13 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?

14 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)

15 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]); }

16 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)); }

17 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

18 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]); }

19 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)); }

20 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

21 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)

22 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); }

23 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; }

24 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--; }

25 Reversing an array public static void Swap (int array[], int i, int j) { int temp; temp = array[i]; array[i] = array[j]; array[j] = temp; }

26 Reversing an array public static void PrintArray (int array[], int size) { int i; for (i=0;i<size;i++) { System.out.println (array[i]); } } // end class

27 Bubble sort class BubbleSort { public static void main (String arg[]) { int size = 20; double array[] = new double[size]; Initialize (array, size); // not shown PrintArray (array, size); // not shown Sort (array, size); PrintArray (array, size); // not shown }

28 Bubble sort public static void Sort (double array[], int size) { int i, j; for (i=1;i<=size-1;i++) { for (j=0;j<=size-2;j++) { // better: j<=size-i-1 CompareAndSwap (array, j, j+1); } // Invariant: maximum of sub-array is // in position size-i }

29 Bubble sort public static void CompareAndSwap (double array[], int p, int q) { double temp; if (array[p] > array[q]) { temp = array[p]; array[p] = array[q]; array[q] = temp; } } // end class (How many comparisons?)

30 Insertion sort public static void Sort (double array[], int size) { int i, j; for (i=1; i<size; i++) { for (j=0; array[i] > array[j]; j++); if (j < i) { Insert (array, i, j); } // Invariant: the first i+1 element // are sorted }

31 Insertion sort public static void Insert (double array[], int oldpos, int newpos) { int i; double candidate = array[oldpos]; for (i=oldpos-1; i>=newpos; i--) { array[i+1] = array[i]; } array[i+1] = candidate; }

32 Insertion sort How many comparisons? –Need to consider worst case –What does the array look like in the worst case? –What is the best case? Just the number of comparisons does not tell you the whole story –How many assignments do you execute?

33 Merging two sorted arrays Suppose we have sorted the first m and the remaining n-m elements of an array separately We need to merge these two sorted halves to get a complete sorted array Assume that everything is sorted in ascending order

34 Merging two sorted arrays public static void Merge (double array[], int start, int m, int n) { // start would be 0 in this case double temp[] = new double[n-start]; int index = 0, index1, index2, i; for (index1=start, index2=m; (index1 < m) && (index2 < n);) { if (array[index1] < array[index2]) { temp[index] = array[index1]; index++; index1++; } else { temp[index] = array[index2]; index++; index2++; } } // continued in next slide

35 Merging two sorted arrays for(;index1<m;index1++,index++) { temp[index] = array[index1]; } for(;index2<n;index2++,index++) { temp[index] = array[index2]; } for (i=start;i<n;i++) { array[i] = temp[i-start]; }

36 Merge sort Recursively sort half of the array separately and merge them class MergeSort { public static void main (String arg[]) { int n = 20; double array[] = new double[n]; Initialize (array, n);// not shown Sort (array, 0, n-1); } // continued in next slide

37 Merge sort public static void Sort (double array[], int start, int end) { if (start < end) { Sort (array, start, start+(end+1- start)/2-1); Sort (array, start+(end+1-start)/2, end); Merge (array, start, start+(end+1- start)/2, end+1); } } // end class

38 Merge sort Running time? Let it be T(n) for an array of size n T(n) = 2T(n/2) + cn for some constant c Solution to this functional equation (or recurrence) is the running time of merge sort T(n) = c’nlog 2 (n) for some constant c’ and large n –I can absorb the base of log in the constant Note that this is the worst case running time of merge sort –Much better than bubble sort and insertion sort which had worst case running time quadratic in n

39 Prime numbers Previously we checked for primality of an integer n by dividing it by all integers up to √n We only need to divide by the primes up to √n Use an array to remember the primes seen so far

40 Prime numbers class PrimeNumbers { // Find all primes up to n public static void main (String arg[]) { int n = 10000; // Assume n > 1 // Use Dusart’s bound (just using n wastes // too much of memory for large n) int maxNumPrimes = (int)((n/Math.log(n))*( /Math.log(n))); int primes[] = new int[maxNumPrimes]; int numPrimesFound = 0; int i; // continued on next slide

41 Prime numbers for (i=2; i<=n; i++) { if (CheckPrimality (i, primes, numPrimesFound)) { primes[numPrimesFound] = i; numPrimesFound++; } PrintPrimes(primes, numPrimesFound); } // end main // continued on next slide

42 Prime numbers public static boolean CheckPrimality (int n, int primes[], int count) { int i; for (i=0; (i<count) && (primes[i] <= Math.sqrt(n)); i++) { if ((n%primes[i])==0) { return false; } return true; } // continued on next slide

43 Prime numbers public static void PrintPrimes (int primes[], int count) { int i, j=0; for (i=0; i<count; i++) { System.out.print (primes[i] + “ ”); j++; if (j==10) { // print 10 primes per line System.out.print (“\n”); j=0; } System.out.print (“\n”); } } // end class