+ All Categories
Home > Documents > Slide 1 of 57. Lecture F - Arrays Unit F1 - Introduction to Arrays.

Slide 1 of 57. Lecture F - Arrays Unit F1 - Introduction to Arrays.

Date post: 21-Dec-2015
Category:
View: 219 times
Download: 1 times
Share this document with a friend
57
Slide 1 of Lecture F - Arrays Lecture F - Arrays Unit F1 - Introduction to Arrays
Transcript

Slide 1 of 57.Lecture F - Arrays

Lecture F - Arrays

Unit F1 - Introduction to Arrays

Slide 2 of 57.Lecture F - Arrays

Lesson or Unit Topic or Objective

Basic Introduction to Arrays

Slide 3 of 57.Lecture F - Arrays

Collections

• Programs usually handle large amounts of data Names of all people in the class A Matrix

• Your program needs to be able to store and handle collections of data items, without giving each data item a separate name.

• Several ways to handle collections in your program Arrays Built in collection library (e.g. class Vector) Linked Data Structures

Slide 4 of 57.Lecture F - Arrays

Arrays

• An array is an ordered list of values• Each value has a numeric index• An array of size N is indexed from 0 to N-1• The following array of integers has a size of 10 and is

indexed from 0 to 9

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

Slide 5 of 57.Lecture F - Arrays

Arrays

• A particular value in an array is referenced using the array name followed by the index in brackets

• For example, the expression

scores[4]

refers to the value 67• That expression represents a place to store a single

integer, can be used wherever an integer variable can• For example, it can be assigned a value, printed, used in

a calculation

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

Slide 6 of 57.Lecture F - Arrays

Arrays

• An array stores multiple values of the same type• That type can be primitive types or object reference• Therefore, we can create an array of integers, or an array

of characters, or an array of String references, etc.• In Java, the array itself is an object• Therefore it is accessed through a reference

Slide 7 of 57.Lecture F - Arrays

Declaring Arrays

• The scores array could be declared as follows:

• Note that the type of the array does not specify its size,

but each object of that type has a specific size• The type of the variable scores is int[] (a reference to

an array of integers)• It is set to refer to a newly instantiated array of 10

integers

int[] scores = new int[10];

Slide 8 of 57.Lecture F - Arrays

Declaring Arrays

• Some examples of array declarations:

float[] prices = new float[500];

boolean[] flags;

flags = new boolean[20];

char[] text = new char[1750];

Slide 9 of 57.Lecture F - Arrays

Reverse

public class Reverse { public static void main(String[] args){ int[] elements; InputRequestor in = new InputRequestor():

int size = in.requestInt(“Enter number of elements:”);

elements = new int[size]; for ( int j=0 ; j<size ; j++ ) elements[j] = in.requestInt(“enter element “ + j); for( int j=size-1 ; j>=0 ; j-- ) System.out.println(elements[j]); }}

Slide 10 of 57.Lecture F - Arrays

DigitsHistogrampublic class DigitsHistogram { public static void main(String[] args) { InputRequestor input = new InputRequestor(); int n = input.requestInt(“Enter a number:”); int[] histogram = new int[10]; while (n>0) { int digit = (int)(n%10); histogram[digit]++; n/=10; } for (int i=0; i<10; i++) { System.out.print(i+” “); for (int j=0; j<histogram[i]; j++) System.out.print(“*”); System.out.println(); } }}

Slide 11 of 57.Lecture F - Arrays

DigitHistogram OutputThe result for the input 20901225321 will be:

0 **

1 **

2 ****

3 *

4

5 *

6

7

8

9 *

Slide 12 of 57.Lecture F - Arrays

Array length

• Each array object has a public field called length that stores the size of the array

• It is referenced through the array name (just like any other object):

scores.length• Note that length holds the number of elements, not the

largest index

Slide 13 of 57.Lecture F - Arrays

Using Array length in loops

• We can now rewrite the printing loop of the previous program:

for (int i=0; i< histogram.length; i++) { output.print(i+” “); for (int j=0; j<histogram[i]; j++) { output.print(“*”); } output.println();}

Slide 14 of 57.Lecture F - Arrays

Initializer Lists

• An initializer list can be used to instantiate and initialize an array in one step

• The values are delimited by braces and separated by commas

• Examples: int[] units = {147, 323, 89, 933, 540};

char[] vowels = {’a’,’o’,’i’,’u’,’e’};

Slide 15 of 57.Lecture F - Arrays

Initializer Lists

• Note that when an initializer list is used: the new operator is not used no size value is specified

• The size of the array is determined by the number of items in the initializer list

• An initializer list can only be used in the declaration of an array

Slide 16 of 57.Lecture F - Arrays

Arrays of Characters vs. Strings

• A String Object is not an Array of characters• Strings are immutable, Array entries can be changed• Strings may be constructed from an array of characters

• There is a natural correspondence a.length vs. s.length() a[i] vs. s.charAt(i)

char[] a = new char[20];// … put something into aString s= new String(a)

Slide 17 of 57.Lecture F - Arrays

FindVowels

public class FindVowels { public static void main(String[] args){ char[] vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}; InputRequestor in = new InputRequestor(); String s = in.requestString(“Enter a word:”);

for (int j = 0 ; j < s.length() ; j++) for (int k =0 ; k < vowels.length ; k++) if (s.charAt(j) == vowels[k] ){ System.out.println(“Found a vowel!”); break; } }}

Slide 18 of 57.Lecture F - Arrays

Arrays as Parameters

• A reference to an array can be passed to a method as a parameter

• Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other

• As the method access the array through an alias reference, the content of the array can be changed.

• Of course, an array element can be passed to a method like any other value.

Slide 19 of 57.Lecture F - Arrays

Lecture F - Arrays

Unit F2 – Arrays of Objects

Slide 20 of 57.Lecture F - Arrays

Arrays of Objects

Using arrays of objects

Slide 21 of 57.Lecture F - Arrays

Arrays of Objects

• The elements of an array can be object references• The declaration

reserves space to store 25 references to String objects (initially all the references are null)

• It does NOT create the String objects themselves• Each object stored in an array must be instantiated

separately

String[] words = new String[25];

Slide 22 of 57.Lecture F - Arrays

TurtleJungle

public class TurtleJungle { static final int STEP = 5; public static void main(String[] args) { InputRequestor in = new InputRequestor(); int numberOfTurtles = in.requestInt(“Number of turtles:”); Turtle[] turtles = new Turtle[numberOfTurtles]; for (int i=0; i<turtles.length; i++) { turtles[i] = new Turtle(); turtles[i].turnLeft((int)(Math.random()*360)); turtles[i].tailUp(); } while(true) for (int i=0; i<turtles.length; i++) turtles[i].moveForward(STEP); }}

Slide 23 of 57.Lecture F - Arrays

Multidimensional Arrays

• A one-dimensional array stores a simple list of values• A two-dimensional array can be thought of as a table of

values, with rows and columns• A two-dimensional array element is referenced using two

index values• A two-dimensional array in Java is an array of arrays• Two ways to construct a multidimensional array

Construct each row explicitly – each row may have a different length

Use a shorthand for square matrices

Slide 24 of 57.Lecture F - Arrays

Diagonal Matrix

public class DiagonalMatrix { public static void main(String[] args){

int[][] mat = new int[10][]; for (int j = 0 ; j < mat.length ; j++) mat[j] = new int[j+1]; for (int j = 0 ; j < mat.length ; j++) for (int k = 0 ; k < mat[j].length ; k++) mat[j][k] = j*k;

// …}

Slide 25 of 57.Lecture F - Arrays

MultiplicationTable

public class MultiplicationTable { public static void main(String[] args){

int[][] table = new int[10][10]; for (int j = 0 ; j < table.length ; j++) for (int k = 0 ; k < table[0].length ; k++) table[j][k] = j*k; for (int j = 0 ; j < table.length ; j++){ for (int k = 0 ; k < table[j].length ; k++) System.out.print(table[j][k] + “ ”); System.out.println(); } }}

Slide 26 of 57.Lecture F - Arrays

Initializing Multidimensional Arrays

• An initializer list can be used to create and set up a multidimensional array

• Each element in the list is itself an initializer list

int[][] hadamard = { { 1, 1, 1, 1}, {-1, 1, -1, 1}, {-1, -1, 1, 1}, {-1, -1, -1, 1} };

Slide 27 of 57.Lecture F - Arrays

Command Line arguments

• When a java program is activated from the shell, the user can pass parameters to it. java MyClass parameters

• The OS shell breaks the line (after the class name) into words.

• The static void main(String) method receives these words in an array of Strings.

Slide 28 of 57.Lecture F - Arrays

EchoTwice

public class EchoTwice { public static void main(String[] args){ for(int i=0 ; i<args.length ; i++) { for(int j=0; j<2 ; j++) System.out.print(args[i]); System.out.println(); } }}

Slide 29 of 57.Lecture F - Arrays

Running EchoTwice

Slide 30 of 57.Lecture F - Arrays

Lecture F - Arrays

Unit F3 - Polynomial Class Example

Slide 31 of 57.Lecture F - Arrays

Polynomial Example

An example of an object that contains

an array

Slide 32 of 57.Lecture F - Arrays

Arrays in Objects

• Many objects hold a large amount of data in them• In many such cases the data is simply kept in a field that

is an array• Usually, when the object is constructed, the array should

be allocated• Here we provide an example

Slide 33 of 57.Lecture F - Arrays

Polynomial

/** * A polynomial. A real valued function of the form * f(x)=a0+a1x+a2x^2+...+an*x^n. */public class Polynomial {

// coefficients[i] is the coefficient of x^i private double[] coefficients;

Slide 34 of 57.Lecture F - Arrays

Polynomial constructor

/** * Constructs a polynomial from the given array of * coefficients. * @param coefficients The coefficients of * of the polynomial. */ public Polynomial(double[] coefficients) { this.coefficients = new double[coefficients.length]; for(int i=0 ; i<coefficients.length ; i++) this.coefficients[i]=coefficients[i];

}

Slide 35 of 57.Lecture F - Arrays

valueAt

/** * Computes the value of this polynomial at a * given point. * @return The value of this polynomial at x. */ public double valueAt(double x) { double value = 0.0; double power = 1.0; for (int i=0; i<coefficients.length; i++) { value += coefficients[i]*power; power *= x; } return value; }

Slide 36 of 57.Lecture F - Arrays

getDegree

/** * Returns the degree of the polynomial. * @return The degree of the polynomial. */ public int getDegree() { int degree = coefficients.length-1; while (coefficients[degree]==0.0) { degree--; } return degree; }

Slide 37 of 57.Lecture F - Arrays

plus

/** * Computes the polynomial resulting from the addition * of this polynomial and p. The sum is returned, but * the value of this polynomial is not changed */ public Polynomial plus(Polynomial p) { int degree = Math.max(getDegree(), p.getDegree()); double[] sum = new double[degree]; for (int i=0; i<degree; i++) sum[i] = coefficients[i] + p.coefficients[i]; return new Polynomial(coefficients);}

Slide 38 of 57.Lecture F - Arrays

getCoefficients

/** * Returns the coefficients of the polynomial. */ public double[] getCoefficients() { double[] copy = new double[coefficients.length]; System.arraycopy(coefficients, 0, copy, 0, coefficients.length); return coefficients; }}// class set

Slide 39 of 57.Lecture F - Arrays

PolynomialUseExample

// Prints a table of values for x^3-2x^2+5x+7class PolynomialUseExample { static final double LOWER_LIMIT = -5.0; static final double UPPER_LIMIT = 5.0; static final double STEP = 1.0;

public static void main(String[] args) { double[] coefficients = {7.0, 5.0, -2.0, 1.0}; Polynomial p = new Polynomial(coefficients); System.out.println(“x \t y”); for (double x=LOWER_LIMIT; x<=UPPER_LIMIT; x+=STEP) { double y = p.valueAt(x); System.out.println(x+” \t “+y); } }}

Slide 40 of 57.Lecture F - Arrays

Lecture F - Arrays

Unit F4 - Sorting and Searching

Slide 41 of 57.Lecture F - Arrays

Sorting & Searching

How and why to sort

And how to search a sorted array

Slide 42 of 57.Lecture F - Arrays

The Sorting problem

• One of the most common computational tasks• Input: an array of numbers• Output: the numbers in the array re-ordered so they would

be in increasing order• Example: {4, 1, 6, 1, 3} {1, 1, 3, 4, 6}• May be applied to an array of any type with total order

Strings: “hello” < “hi” < “there” Fractions: ¼ < 1/3 < ½ < 2/3

• Our examples will sort integers; easy to change to other types.

• Later in the course we will learn how to write a “generic” sorter that applies to all appropriate types

Slide 43 of 57.Lecture F - Arrays

Sorting Algorithms

• Simple Sorting Algorithms Selection sort Insertion sort Bubble sort

• Efficient Sorting algorithms Merge sort Quick sort Heap sort

• Sorting Algorithms for small domains• Out of memory sorting • Parallel sorting• Distributed sorting

Slide 44 of 57.Lecture F - Arrays

Selection Sortpublic class SelectionSort{ public static void main(String[] args) { int[] test = {8, 4, 6, 9, 3,2,2}; selectionSort(test); for (int j = 0 ; j < test.length ; j++) System.out.println(test[j]); } public static void selectionSort (int[] a) { for (int j = 0 ; j < a.length-1 ; j++) { // find index of minimal element in a[j]…a[length] int min = j; for (int k = j+1 ; k < a.length ; k++ ) if (a[k] < a[min]) min = k; // switch minimal element to j’th place if (min != j) { int temp = a[min] ; a[min] = a[j] ; a[j] = temp; } } }}

Slide 45 of 57.Lecture F - Arrays

Sample run

The algorithm for {8,4,6,9,3,5,2} will be:

j min a[]

0 6 2,4,6,9,3,5,8

1 4 2,3,6,9,4,5,8

2 4 2,3,4,9,6,5,8

3 5 2,3,4,5,6,9,8

4 6 2,3,4,5,6,8,9

for (int j = 0 ; j < a.length-1 ; j++) { int min = j; for (int k = j+1 ; k < a.length ; k++ ) if (a[k] < a[min]) min = k; if (min != j) { int temp = a[min] ; a[min] = a[j] ; a[j] = temp; }}

Slide 46 of 57.Lecture F - Arrays

Running Time Analysis

• If N is the input length then the outer loop runs N-1 iterations, j=0 … N-1

• In iteration j the inner loop runs for N-j-1 iterations• Each inner loop takes O(1) time• Total time is O-of:

)(2)1(1...)2()1( 2NONNNN

for (int j = 0 ; j < a.length-1 ; j++) { min = j; for (int k = j+1 ; k < a.length ; k++ ) if (a[k] < a[min]) min = k; if (min != j) { int temp = a[min] ; a[min] = a[j] ; a[j] = temp; } }

Slide 47 of 57.Lecture F - Arrays

Merge Sortpublic static void mergeSort (int[] a) { sort(a,0,a.length-1); }private static void sort(int a[], int low, int high) { if (low >= high ) return; int med = (low + high)/2; sort(a, low, med); sort(a, med+1, high); merge(a, low, med, high);}private static void merge(int[] a, int low, int med, int high) { int[] temp = new int [high-low + 1]; int i = 0 , j = low , k = med + 1; while (i < temp.length) { if (k > high || (j<= med && a[j] < a[k])) temp[i++] = a[j++]; else temp[i++] = a[k++]; } for (int i = 0; i < temp.length ; i++) a[low + i] = temp[i];}

Slide 48 of 57.Lecture F - Arrays

Sample Run if (low >= high ) return; int med = (low + high)/2; sort(a, low, med); sort(a, med+1, high); merge(a, low, med, high);

The algorithm for {23,14,21,9} will be:

Recursion Level low high med

level: 0 0 3 1

level: 1 0 1 0

level: 2 0 0

level: 2 1 1

level: 1 2 3 2

level: 2 2 2

level: 2 3 3

Slide 49 of 57.Lecture F - Arrays

Sample Run

2314219

2314 219

23 14 921

1423 912

9142123

sort(a,0,3);

sort(a,0,1); sort(a,2,3);

sort(a,0,0); sort(a,1,1); sort(a,2,2); sort(a,3,3);

merge(a,0,0,1);merge(a,0,1,3);

merge(a,2,2,3);

Slide 50 of 57.Lecture F - Arrays

Running Time Analysis

• merge(a, low, med, high) runs in O(m) time, where m=high-low is the size of the input to merge().

• The running of sort(a, low, high) is thus given by the recursion T(m)=2T(m/2)+O(m), where m=high-low is the size of the input to sort()

• The solution of this recursion is T(n)=O(n log n)

private static void sort(int a[], int low, int high){ if (low >= high ) return; int med = (low + high)/2; sort(a, low, med); sort(a, med+1, high); merge(a, low, med, high);}

Slide 51 of 57.Lecture F - Arrays

Solving the recursion

• Theorem: if for all n>2, then

For all n>2,

• Proof by induction. Basis n=2: Induction step:

CT )2(CnnTnT )2/(2)(

nCnnT 2log)(

nCn

CnCnnCn

CnnnC

CnnTnT

2

2

2

log

log

)2/(log)2/(2

)2/(2)(

2log2)2( 2CCT

Slide 52 of 57.Lecture F - Arrays

Binary search /** find the index of x in the sorted array a. -1 if * not found */ public static int find(int x, int[] a) { int low = 0; int high = a.length – 1; while (low <= high) { int med = (low + high) / 2; if (x == a[med]) return med; else if (x < a[med]) high = med - 1; else low = med + 1; } return -1; }

Slide 53 of 57.Lecture F - Arrays

Sample run

Search for 57 in {14,16,18,29,33,35,42,45,57,70}:

Recursion Level low high med

0 0 9 4

1 5 9 7

2 8 9 8

while (low <= high) { int med = (low + high) / 2; if (x == a[med]) return med; else if (x < a[med]) high = med - 1; else low = med + 1;

Slide 54 of 57.Lecture F - Arrays

Running time analysis

• How many iterations of the loop can we have? Each iteration the value of (high-low) decreases by a factor of 2 We stop when high<low one iteration after high-low < 1 The number of iterations is at most log2N, where N = a.length()

• The running time is O(log N)

while (low <= high) { int med = (low + high) / 2; if (x == a[med]) return med; else if (x < a[med]) high = med - 1; else low = med + 1;

Slide 55 of 57.Lecture F - Arrays

Binary search – recursive version /** find the index of x in the sorted array a. -1 if not found */ public static int find(int x, int[] a) { return find(x, a, 0, a.length - 1); }

// find x in a[low … high]. -1 if not found. private static int find(int x, int a, int low, int high) { if (low > high) return -1; int med = (low + high) / 2; if (x == a[med]) return med; else if (x < a[med]) return find(x, low, med-1); else return find(x, med+1, high); }

Slide 56 of 57.Lecture F - Arrays

Sample run

Search for 29 in {14,16,18,29,33,35,42,45,57,70}:

Recursion Level low high med

0 0 9 4

1 0 3 1

2 2 3 3

3 3 3 3

if (low > high) return -1; int med = (low + high) / 2; if (x == a[med]) return med; else if (x < a[med]) return find(x, low, med-1); else return find(x, med+1, high);

Slide 57 of 57.Lecture F - Arrays

Lecture F - Arrays


Recommended