68
1 Arrays

1 Arrays. 2 Background Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

Embed Size (px)

DESCRIPTION

3 Array variable definition styles  Without initialization Type of values in list Name of list Brackets indicate array variable being defined ElementType [ ] id; int [] a; int a[];

Citation preview

Page 1: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

1

Arrays

Page 2: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

2

Background Programmer often need the ability to represent a group of

values as a list List may be one-dimensional or multidimensional

Java provides arrays and the collection classes The Vector class is an example of a collection class

Consider arrays first

Page 3: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

3

Array variable definition styles Without initialization

Type ofvalues in

list

Name oflist

Bracketsindicate arrayvariable being

defined

ElementType [ ] id;

int [] a;int a[];

Page 4: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

4

Array variable definition styles With initialization

ElementType[ ] id = new ElementType [n];

Nonnegative integer expression specifying thenumber of elements in the array

Reference to a new array of nelements

Page 5: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

5

Example Definitions

char[] c;int[] value = new int[10];

Causes Array object variable c is un-initialized Array object variable v references a new ten element list

of integers Each of the integers is default initialized to 0

value 0 0 0 0 0

-c

Page 6: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

6

Basic terminology List is composed of elements

Elements in a list have a common name

The list as a whole is referenced through the common name

List elements are of the same type — the base type

Elements of a list are referenced by subscripting (indexing) the common name

Page 7: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

7

Java array features Subscripts are denoted as expressions within brackets: [ ] Base (element) type can be any type Size of array can be specified at run time

This is different that pure C! (for the most part, at least) Index type is integer and the index range must be 0 ... n-1

Where n is the number of elements Automatic bounds checking

Ensures any reference to an array element is valid Data field length specifies the number of elements in the list Array is an object

Has features common to all other objects

Page 8: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

8

Considerint[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

v 00 0 00 0 00 00

v[2]v[0] v[1] v[5]v[3] v[4] v[7]v[6] v[9]v[8]

int[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

v 01 0 00 0 00 00

v[2]v[0] v[1] v[5]v[3] v[4] v[7]v[6] v[9]v[8]

int[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

v 01 0 00 0 50 00

v[2]v[0] v[1] v[5]v[3] v[4] v[7]v[6] v[9]v[8]

int[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

v 81 0 00 0 50 00

v[2]v[0] v[1] v[5]v[3] v[4] v[7]v[6] v[9]v[8]

int[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

v 81 0 06 0 50 00

v[2]v[0] v[1] v[5]v[3] v[4] v[7]v[6] v[9]v[8]

int[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

v 81 0 06 0 50 012

v[2]v[0] v[1] v[5]v[3] v[4] v[7]v[6] v[9]v[8]

int[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

v 81 0 06 0 50 012

v[2]v[0] v[1] v[5]v[3] v[4] v[7]v[6] v[9]v[8]

8 is displayed

int[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

v 81 0 06 3 50 012

v[2]v[0] v[1] v[5]v[3] v[4] v[7]v[6] v[9]v[8]

Suppose 3 is extracted

int[] v = new int[10];int i = 7;int j = 2;int k = 4;v[0] = 1;v[i] = 5;v[j] = v[i] + 3;v[j+1] = v[i] + v[0];v[v[j]] = 12;System.out.println(v[2]);v[k] = stdin.nextInt();

Page 9: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

9

Consider Segment

int[] b = new int[100];b[-1] = 0;b[100] = 0;

Causes Array variable to reference a new list of 100 integers

Each element is initialized to 0 Two exceptions to be thrown

-1 is not a valid index – too small 100 is not a valid index – too large

IndexOutOfBoundsException

Page 10: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

1010

Today’s demotivatorsToday’s demotivators

Page 11: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

11

ConsiderPoint[] p = new Point[3];p[0] = new Point(0, 0);p[1] = new Point(1, 1);p[2] = new Point(2, 2);p[0].setX(1);p[1].setY(p[2].getY());Point vertex = new Point(4,4);p[1] = p[0];p[2] = vertex;

p

p[0] p[1] p[2]

null null null

Point: (0, 0)

p

p[0] p[1]

Point: (1, 1) Point: (2, 2)

p[2]

Point: (1, 0)

p

p[0] p[1]

Point: (1, 1) Point: (2, 2)

p[2]

Point: (1, 0)

p

p[0] p[1]

Point: (1, 2) Point: (2, 2)

p[2]

Point: (1, 0)

p

p[0] p[1]

Point: (1, 2) Point: (2, 2)

p[2]

vertex

Point: (4, 4)

Point: (1, 0)

p

p[0] p[1]

Point: (2, 2)

p[2]

vertex

Point: (4, 4)

Point: (1, 0)

p

p[0] p[1] p[2]

vertex

Point: (4, 4)

Point[] p = new Point[3];p[0] = new Point(0, 0);p[1] = new Point(1, 1);p[2] = new Point(2, 2);p[0].setX(1);p[1].setY(p[2].getY());Point vertex = new Point(4,4);p[1] = p[0];p[2] = vertex;

Page 12: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

12

Explicit initialization Syntax

ElementType[] id = { exp0 , exp1 , ... expn-1 };

id references an array of n elements. id[0] hasvalue exp0, id[1] has value exp1, and so on.

Each expi is an expression thatevaluates to type ElementType

Page 13: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

13

Explicit initialization Example

String[] puppy = { “pika“, “arlo“, “schuyler", “nikki" };

int[] unit = { 1 };

Equivalent toString[] puppy = new String[4];puppy[0] = “pika"; puppy[1] = “arlo";puppy[2] = “schuyler"; puppy[3] = “nikki";

int[] unit = new int[1];unit[0] = 1;

Page 14: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

14

Array members Member length

Size of the arrayfor (int i = 0; i < puppy.length; ++i) {

System.out.println(puppy[i]);}

Page 15: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

15

Array members Member clone()

Produces a shallow copyPoint[] u = { new Point(0, 0), new Point(1, 1)};Point[] v = u.clone();

v[1] = new Point(4, 30);

Point: (0, 0) Point: (1, 1)

u

u[0] u[1]

Point: (0, 0)

v

v[0] v[1]

Point: (1, 1)

u

u[0] u[1]

Point: (0, 0)

v

v[0] v[1]

Point: (1, 1)

u

u[0] u[1]

Point: (4, 30)

Point[] u = { new Point(0, 0), new Point(1, 1)};Point[] v = u.clone();

v[1] = new Point(4, 30);

Page 16: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

16

Making a deep copy Example

Point[] w = new Point[u.length];for (int i = 0; i < u.length; ++i) {

w[i] = (Point) u[i].clone();}

Page 17: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

17

Making a deep copy

Point: (0, 0)

w

w[0] w[1]

Point: (2, 1) Point: (2, 2)

w[2]

u

u[0] u[1] u[2]

Point: (0, 0) Point: (2, 1) Point: (2, 2)

Page 18: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

19

Review of last time Creating an array:

int[] foo = new int[10];

Accessing an array:foo[3] = 7;System.out.print (foo[1]);

Creating an array:String[] bar = new String[10];

Accessing an array:bar[3] = “qux”;System.out.println (bar[1]);

Page 19: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

20

How Java represents arrays Consider

int[] a = { 1, 2, 3, 4, 5 };

a 1 2 3 4 5+ …

Array

- length = 5- data = 1 2 3 4 5

Page 20: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

21

More about how Java represents Arrays Consider

int[] a;int[] b = null;int[] c = new int[5];int[] d = { 1, 2, 3,

4, 5 };a = c;d = c;

1 2 3 4 5

0 0 0 0 0

a -

b null

c

d

int[] a;int[] b = null;int[] c = new int[5];int[] d = { 1, 2, 3, 4, 5 };a = c;d = c;

Page 21: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

22

System.out.println("Enter search value (number): ");int key = stdin.nextInt();

int i;for (i = 0; i < data.length; ++i) {

if (key == data[i]) {break;}

}

if (i != data.length) {System.out.println(key + " is the " + i+ "-th element");

}else {

System.out.println(key + " is not in the list");}

++i

System.out.println("Enter search value (number): ");int key = stdin.nextInt();

int i;

if (key == data[i]) {break;

if (i != data.length) {System.out.println(key + " is the " + i

+ "-th element");}

i < data.length i = 0

Searching for a value

data 54 9

20 1

key 5

i -

data 54 9

20 1

key 5

i 0

data 54 9

20 1

key 5

i 0

data 54 9

20 1

key 5

i 0

data 54 9

20 1

key 5

i 1

data 54 9

20 1

key 5

i 1

data 54 9

20 1

key 5

i 1

data 54 9

20 1

key 5

i 2

data 54 9

20 1

key 5

i 2

data 54 9

20 1

key 5

i 2

data 54 9

20 1

key 5

i 2

data 54 9

20 1

key 5

i 2

Page 22: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

23

Searching for the minimum value Segment

int minimumSoFar = sample[0];for (int i = 1; i < sample.length; ++i) {

if (sample[i] < minimumSoFar) {minimumSoFar = sample[i];

}}

Page 23: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

24

ArrayTools.java – outline

public class ArrayTools { // class constant private static final int MAX_LIST_SIZE = 1000; // sequentialSearch(): examine unsorted list for key public static int sequentialSearch[] data, int key) { ... // putList (): prints list to screen public static void putList(int[] data) { ... // getList(): extract and return up to MAX_LIST_SIZE values public static int[] getList() throws IOException { ... // reverse(): reverses the order of the element values public static void reverse(int[] list) { ... // binarySearch(): examine sorted list for a key public static int binarySearch(char[] data, char key) { ...}

Page 24: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

25

ArrayTools.java method putList()public static void putList(int[] data) {

for (int i = 0; i < data.length; ++i) {System.out.println(data[i]);

}}

Considerint[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 };putList(score);

Page 25: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

26

ArrayTools.java method getList()public static int[] getList() {

Scanner stdin = new Scanner (System.in);int[] buffer = new int[MAX_LIST_SIZE];int listSize = 0;for (int i = 0; (i < MAX_LIST_SIZE) && stdin.hasNext(); ++i) {

buffer[i] = stdin.nextInt();++listSize;

}int[] data = new int[listSize];for (int i = 0; i < listSize; ++i) {

data[i] = buffer[i];}return data;

}

Page 26: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

27

ArrayTools.java method reverse()public static void reverse(int[] data) {

int[] clone = data.clone();for ( int i = 0; i < clone.length; ++i ) {

data[i] = clone[clone.length-1-i];}

}

Considerint[] foo = { 1, 2, 3, 4, 5 };reverse (foo);putList (foo);

Page 27: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

28

Demo.javapublic class Demo {

// main(): application entry point public static void main(String[] args) {

System.out.println("");System.out.println("Enter list of integers:");int[] numbers = ArrayTools.getList();System.out.println("");System.out.println("Your list");ArrayTools.putList(numbers);ArrayTools.reverse(numbers);System.out.println("");System.out.println("Your list in reverse");ArrayTools.putList(numbers);System.out.println();

}}

Page 28: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional
Page 29: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

30

ArrayTools.java method sequentialSearch()public static int sequentialSearch(int[] data, int key) {

for (int i = 0; i < data.length; ++i) {if (data[i] == key) {return i;}}

return -1;}

Considerint[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 };int i1 = sequentialSearch(score, 11);int i2 = sequentialSearch(score, 30);

data 826 9 8511 29 2911 91

20 1 53 4 76 8

key 11

Page 30: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

3131

Yale vs. HarvardYale vs. Harvard

Web references: http://www.harvardsucks.org/, Web references: http://www.harvardsucks.org/, http://www.yaledailynews.com/article.asp?AID=27506http://www.yaledailynews.com/article.asp?AID=27506

Page 31: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

32

Sorting Problem

Arranging elements so that they are ordered according to some desired scheme Standard is non-decreasing order

Why don't we say increasing order?

Major tasks Comparisons of elements Updates or element movement

Page 32: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

33

Selection sorting Algorithm basis

On iteration i, a selection sorting method: Finds the element containing the ith smallest value of

its list v and exchanges that element with v[i]

Example – iteration 0 Swaps smallest element with v[0] This results in smallest element being in the correct place

for a sorted result

v ‘E'‘Q' 'W' 'Y''R' 'T' 'I''U' 'P''O'

20 1 53 4 76 98

Page 33: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

34

Selection sorting Algorithm basis

On iteration i, a selection sorting method: Finds the element containing the ith smallest value of

its list v and exchanges that element with v[i]

Example – iteration 0 Swaps smallest element with v[0] This results in smallest element being in the correct place

for a sorted result

v ‘E'‘Q' 'W' 'Y''R' 'T' 'I''U' 'P''O'

20 1 53 4 76 98

Page 34: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

35

Selection sorting Algorithm basis

On iteration i, a selection sorting method: Finds the element containing the ith smallest value of

its list v and exchanges that element with v[i]

Example – iteration 0 Swaps smallest element with v[0] This results in smallest element being in the correct place

for a sorted result

v 'Q''E' 'W' 'Y''R' 'T' 'I''U' 'P''O'

20 1 53 4 76 98

Page 35: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

36

Selection sorting Algorithm basis

On iteration i, a selection sorting method: Finds the element containing the ith smallest value of

its list v and exchanges that element with v[i]

Example – iteration 1 Swaps second smallest element with v[1] This results in second smallest element being in the

correct place for a sorted result

v 'Q''E' 'W' 'Y''R' 'T' 'I''U' 'P''O'

20 1 53 4 76 98

Page 36: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

37

Selection sorting Algorithm basis

On iteration i, a selection sorting method: Finds the element containing the ith smallest value of

its list v and exchanges that element with v[i]

Example – iteration 1 Swaps second smallest element with v[1] This results in second smallest element being in the

correct place for a sorted result

v 'Q''E' 'I' 'Y''R' 'T' 'W''U' 'P''O'

20 1 53 4 76 98

Page 37: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

38

ArrayTools.java selection sortingpublic static void selectionSort(int[] v) {

for (int i = 0; i < v.length-1; ++i) {

// find the location of the ith smallest elementint spot = i;for (int j = i+1; j < v.length; ++j) { if (v[j] < v[spot]) { // is current location ok? // update spot to index of smaller element

spot = j; }}

// spot is now correct, so swap elementsint rmbr = v[i];v[i] = v[spot];v[spot] = rmbr;

}}

Page 38: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

39

Iteration i// find the location of the ith smallest element int spot = i;for (int j = i+1; j < v.length; ++j) {

if (v[j] < v[spot]) // is spot ok?// update spot with index of smaller elementspot = j;

}

// spot is now correct, swap elements v[spot] and v[i]

Page 39: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

40

Quick surveyQuick survey How are we doing with arrays?How are we doing with arrays?a)a) Very wellVery wellb)b) With some review, I’ll be goodWith some review, I’ll be goodc)c) Not reallyNot reallyd)d) Not at allNot at all

Page 40: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

4141

Privacy policyPrivacy policy From time to time, in order to improve Google Gulp's From time to time, in order to improve Google Gulp's

usefulness for our users, Google Gulp will send usefulness for our users, Google Gulp will send packets of data related to your usage of this product packets of data related to your usage of this product from a wireless transmitter embedded in the base of from a wireless transmitter embedded in the base of your Google Gulp bottle to the GulpPlex™, a heavily your Google Gulp bottle to the GulpPlex™, a heavily guarded, massively parallel server farm whose guarded, massively parallel server farm whose location is known only to Eric Schmidt, who carries location is known only to Eric Schmidt, who carries its GPS coordinates on a 64-bit-encrypted smart card its GPS coordinates on a 64-bit-encrypted smart card locked in a stainless-steel briefcase handcuffed to locked in a stainless-steel briefcase handcuffed to his right wrist. No personally identifiable information his right wrist. No personally identifiable information of any kind related to your consumption of Google of any kind related to your consumption of Google Gulp or any other current or future Google Foods Gulp or any other current or future Google Foods product will ever be given, sold, bartered, auctioned product will ever be given, sold, bartered, auctioned off, tossed into a late-night poker pot, or otherwise off, tossed into a late-night poker pot, or otherwise transferred in any way to any untrustworthy third transferred in any way to any untrustworthy third party, ever, we swear. See our Privacy Policy.party, ever, we swear. See our Privacy Policy.

April Fools Day JokesApril Fools Day Jokes

http://www.google.com/googlegulp/(or do a Google search for ‘gulp’)

Page 41: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

4343

Google Maps…Google Maps…

Page 42: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

44

Binary search Given a list, find a specific element in the list

List MUST be sorted!

Each time it iterates through, it cuts the list in half

A binary search is MUCH faster than a sequential search

Page 43: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

45

Binary search use The ‘BS’ in BSDemo is for Binary Search, mind you

public class BSDemo {public static void main(String[] args) {int[] numbers = { 9, 3, 1, 8, 4, 6, 10, 2 };System.out.println ("The original list of numbers:");ArrayTools.putList(numbers);System.out.println();

ArrayTools.selectionSort(numbers);System.out.println ("The sorted list of numbers:");ArrayTools.putList(numbers);System.out.println();

System.out.println ("Searching for 0: " + ArrayTools.binarySearch(numbers, 0));System.out.println ("Searching for 1: " + ArrayTools.binarySearch(numbers, 1));System.out.println ("Searching for 4: " + ArrayTools.binarySearch(numbers, 4));System.out.println ("Searching for 5: " + ArrayTools.binarySearch(numbers, 5));System.out.println ("Searching for 6: " + ArrayTools.binarySearch(numbers, 6));System.out.println ("Searching for 10: " + ArrayTools.binarySearch(numbers, 10));System.out.println ("Searching for 11: " + ArrayTools.binarySearch(numbers, 11));}

}

Page 44: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

46

Binary search use demo…

Page 45: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

47

Binary searchpublic static int binarySearch (int[] data, int key) {

int i = 0; // left endpoint of search intervalint j = data.length-1; // right endpoint of search intervalwhile ( i < j ) { int m = (i+j)/2; if ( key > data[m] ) {i = m+1; } else {j = m; }}if ( key == data[i] ) { return i;} else { return -1;}

}

Page 46: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

48

if ( key == data[i] ) {return i;

} else {return -1;

}

if ( key == data[i] ) {return i;

} else {return -1;

}

int i = 0;int j = data.length-1;int i = 0;int j = data.length-1;

while ( i < j ) {int m = (i+j)/2;if ( key > data[m] ) { i = m+1;} else { j = m;}

}

while ( i < j ) {int m = (i+j)/2;if ( key > data[m] ) { i = m+1;} else { j = m;}

}

Binary search, take 1

2 4 6 8 10 12 14 16 18 20

a0 a1 a2 a3 a4 a5 a6 a7 a8 a9

i jm

public static int binarySearch (int[] data, int key) {

0

key 14

945 7 76 656

returns: 6

data

Page 47: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

49

if ( key == data[i] ) {return i;

} else {return -1;

}

if ( key == data[i] ) {return i;

} else {return -1;

}

int i = 0;int j = data.length-1;int i = 0;int j = data.length-1;

while ( i < j ) {int m = (i+j)/2;if ( key > data[m] ) { i = m+1;} else { j = m;}

}

while ( i < j ) {int m = (i+j)/2;if ( key > data[m] ) { i = m+1;} else { j = m;}

}

Binary search, take 2

2 4 6 8 10 12 14 16 18 20

a0 a1 a2 a3 a4 a5 a6 a7 a8 a9

i jm

public static int binarySearch (int[] data, int key) {

0

key 15

945 7 76

returns: -1

data

Page 48: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

50

Binary search A somewhat alternative view of what a binary search does…

Page 49: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

51

How long does a binary search take? Given a array of 64 elements

1st iteration cuts the array to 32 2nd iteration cuts the array to 16 3rd to 8 4th to 4 5th to 2 6th to 1

Given a array of 1024 elements 1st iteration cuts the array to 512 ... 10th iteration cuts the list to 1 element

Thus, the binary search takes log2 n iterations! Where n is the size of the array

Page 50: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

52

Binary search vs. sequential search Assume the array has n elements

Sequential search can take (in the worst-case) n iterations to find the element

Binary search can take (in the worst case) log2 n iterations to find the element

Consider a list of 1 million elements Binary search takes about 20 iterations Sequential search takes 1,000,000 iterations

Consider a list of 1 trillion elements Binary search takes about 40 iterations Sequential search takes 1,000,000,000,000 iterations

Page 51: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

53

Quick surveyQuick survey How are we doing with binary How are we doing with binary

searches?searches?a)a) Very wellVery wellb)b) With some review, I’ll be goodWith some review, I’ll be goodc)c) Not reallyNot reallyd)d) Not at allNot at all

Page 52: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

5454

Becoming an IEEE authorBecoming an IEEE author

Page 53: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

5555

Page 54: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

56

Multidimensional arrays Many problems require information be organized as a two-

dimensional or multidimensional list

Examples Matrices Graphical animation Economic forecast models Map representation Time studies of population change Microprocessor design

Page 55: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

57

Example Segment

int[][] m = new int[3][];m[0] = new int[4];m[1] = new int[4];m[2] = new int[4];

Produces

When an array is created, each

value is initialized!

mm[0] m[1] m[2]

0 0 0 0 0 0 0 0

00 0 0

m[2][0] m[2][1] m[2][2] m[2][3]

m[0][0] m[0][1] m[0][2] m[0][3] m[1][0] m[1][1] m[1][2] m[1][3]

m

Page 56: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

58

Example Alternative

int[][] m = new int[3][4];

Produces

mm[0] m[1] m[2]

0 0 0 0 0 0 0 0

00 0 0

m[2][0] m[2][1] m[2][2] m[2][3]

m[0][0] m[0][1] m[0][2] m[0][3] m[1][0] m[1][1] m[1][2] m[1][3]

Page 57: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

59

Multidimensional array visualization A multi-dimensional array declaration (either one):

int[][] m = new int[3][4];

How we visualize it:

0 0 0

0 0 0

0 0 0

0 0 0

0

0

0

0

0

0

0

0

0

0

0

0

or

Page 58: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

60

Example Segment

for (int r = 0; r < m.length; ++r) {for (int c = 0; c < m[r].length; ++c) {

System.out.print("Enter a value: "); m[r][c] = stdin.nextInt();

}}

Page 59: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

61

Example Segment

String[][] s = new String[4][];s[0] = new String[2];s[1] = new String[2];s[2] = new String[4];s[3] = new String[3];

Produces

s

s[0] s[1] s[2]

null nullnull null

null null null

s[3][0] s[3][1] s[3][2]

s[1][0] s[1][1]

s[0][0] s[0][1]

null null null null

s[2][0] s[2][1] s[2][2] s[2][3]

s[3]

Page 60: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

62

Multidimensional array visualization Segment

String[][] s = new String[4][];s[0] = new String[2];s[1] = new String[2];s[2] = new String[4];s[3] = new String[3];

Produces

Called a “ragged” array

0 0 0

0 0 0

0

0

0

0

0

0

0

0

0

0

0

0

0

or

0

0

0

Page 61: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

63

Example Segment

int c[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8, 9}};

Produces

c

c[0] c[1] c[2]

1 23 4

7 8 9

c[3][0] c[3][1] c[3][2]

c[1][0] c[1][1]

c[0][0] c[0][1]

5 6

c[2][0] c[2][1]

c[3]

Page 62: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

64

Matrices A two-dimensional array is sometimes known as a matrix

because it resembles that mathematical concept

A matrix a with m rows and n columns is represented mathematically in the following manner

a1 1 a1 2 a1 n

a2 1 a2 2 a2 n

am 1 am 2 a m n

Page 63: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

65

Matrix addition Definition C = A + B

cij = aij + bij

cij is sum of the elements in the same row and column of A and B

Page 64: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

66

Matrix additionpublic static double[][] add(double[][] a, double[][] b) {

// determine number of rows in solutionint m = a.length;// determine number of columns in solutionint n = a[0].length;// create the array to hold the sumdouble[][] c = new double[m][n];// compute the matrix sum row by rowfor (int i = 0; i < m; ++i) {

// produce the current rowfor (int j = 0; j < n; ++j) {

c[i][j] = a[i][j] + b[i][j];}

}return c;

}

Page 65: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

67

Quick surveyQuick survey I felt I understood the material in this I felt I understood the material in this

slide set…slide set…a)a) Very wellVery wellb)b) With some review, I’ll be goodWith some review, I’ll be goodc)c) Not reallyNot reallyd)d) Not at allNot at all

Page 66: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

68

Quick surveyQuick survey The pace of the lecture for this The pace of the lecture for this

slide set was…slide set was…a)a) FastFastb)b) About rightAbout rightc)c) A little slowA little slowd)d) Too slowToo slow

Page 67: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

69

Quick surveyQuick survey How interesting was the material in How interesting was the material in

this slide set? Be honest!this slide set? Be honest!a)a) Wow! That was SOOOOOOO cool!Wow! That was SOOOOOOO cool!b)b) Somewhat interestingSomewhat interestingc)c) Rather boringRather boringd)d) ZzzzzzzzzzzZzzzzzzzzzz

Page 68: 1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional

7070

Today’s demotivatorsToday’s demotivators