arrays

122
1 Arrays Chapter 8 Spring 2007 CS 101 Aaron Bloomfield

Upload: brenden-tanner

Post on 30-Dec-2015

31 views

Category:

Documents


3 download

DESCRIPTION

Arrays. Chapter 8 Spring 2007 CS 101 Aaron Bloomfield. Introduction to arrays. 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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Arrays

1

Arrays

Chapter 8Spring 2007CS 101Aaron Bloomfield

Page 2: Arrays

22

Introduction to arraysIntroduction to arrays

Page 3: Arrays

3

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 4: Arrays

4

Example Definitions

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

Causes Array object variable c is un-initialized Array object variable value 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 5: Arrays

5

An array example

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 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 6: Arrays

6

Array variable definition styles Without initialization

Type ofvalues in

list

Name oflist

Bracketsindicate arrayvariable being

defined

ElementType [ ] id;

int [] a;int a[];

Page 7: Arrays

7

Array variable definition styles With initialization

ElementType[ ] id = new ElementType [n];

Nonnegative integer expression specifying thenumber of elements in the array

A new array of nelements

Page 8: Arrays

8

Where we’ve seen arrays public static void main (String[] args)

Thus, the main() method takes in a String array as the parameter

Note that you can also define it as: public static void main (String args[])

or public static void main (String[] foobar)

Page 9: Arrays

9

Basic terminology List is composed of elements

Elements in a list have a common name Example: a[3] = 5; The common name is ‘a’

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 10: Arrays

10

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 Just like Strings indexing!

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 More on this later…

Page 11: Arrays

1111

Today’s site of the dayToday’s site of the day

Link of the day: Link of the day: http://www.spiegel.de/international/zhttp://www.spiegel.de/international/zeitgeist/0,1518,475454,00.htmleitgeist/0,1518,475454,00.html

Page 12: Arrays

13

Review of arrays 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 13: Arrays

14

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 14: Arrays

15

Consider

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;

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 15: Arrays

16

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 16: Arrays

17

Explicit initialization Example

String[] puppy = { “pika”, “mila”, “arlo”, “nikki” };

int[] unit = { 1 };

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

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

Page 17: Arrays

18

Array members Member length

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

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

Note that length is a field, not a method! I.e., it is not puppy.length()

Page 18: Arrays

1919

Chapter 2: Computer bugsChapter 2: Computer bugs

Page 19: Arrays

20

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 20: Arrays

21

Member clone() Produces a shallow copy

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

v[1].setX(10);

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

v[1].setX(10);

Array members

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: (10, 1)

u

u[0] u[1]

Page 21: Arrays

22

Making a deep copy We want to copy the array and all the objects each element

of the array references This is called a deep copy

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

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

Page 22: Arrays

23

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 23: Arrays

24

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 24: Arrays

25

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 25: Arrays

2626

Today’s demotivatorsToday’s demotivators

Page 26: Arrays

27

How are we doing with How are we doing with arrays?arrays?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 27: Arrays

2828

ArrayToolsArrayTools

Page 28: Arrays

29

ArrayTools.java We want to create a series of general utility methods to be

used for arrays

We will put these into an ArrayTools class

Page 29: Arrays

30

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(int[] 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() { ...

// 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 30: Arrays

31

ArrayTools.java method putList() To print the array:

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 31: Arrays

32

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 32: Arrays

34

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 33: Arrays

35

ArrayDemo.javapublic class ArrayDemo {

// 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 34: Arrays
Page 35: Arrays

3737

ArrayTools demo…ArrayTools demo…

ArrayDemo.javaArrayDemo.java

Page 36: Arrays

38

How are we doing with How are we doing with ArrayTools?ArrayTools?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 37: Arrays

3939

A solution to commenting your A solution to commenting your codecode

The commentator: The commentator: http://www.cenqua.com/commentatohttp://www.cenqua.com/commentator/r/

Page 38: Arrays

4040

… … main (String args[])main (String args[])

Page 39: Arrays

41

Consider that main() method again public static void main (String args[])

How does one pass in a parameter to the main method?

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

System.out.println ("Number of paramters to “ + "main(): " + args.length);

if ( args.length > 0 ) {for ( int i = 0; i < args.length; i++ )

System.out.println ("parameter " + i + ": '" + args[i] +

"'");}

}}

Page 40: Arrays

4242

Program DemoProgram Demo

MainParameters.javaMainParameters.java Via JCreatorVia JCreator Via the command lineVia the command line

Page 41: Arrays

4343

Basic array searchingBasic array searching

Page 42: Arrays

44

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 43: Arrays

45

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 44: Arrays

46

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 45: Arrays

47

How are we doing with How are we doing with searching?searching?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 46: Arrays

4848

Follow-up on Knut the polar Follow-up on Knut the polar bear cubbear cub

http://www.comedycentral.com/mothhttp://www.comedycentral.com/motherload/?ml_video=84023erload/?ml_video=84023

Page 47: Arrays

50

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 };int i1 = sequentialSearch(score, 11);

sequentialSearch() finding an element

data 826 9 8511 29

20 1 53 4

key 11

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

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

}}

return -1;}

int i = 0

i < data.length ++i

i 0 1 2 3

i1 3

Page 48: Arrays

51

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 };int i1 = sequentialSearch(score, 30);

sequentialSearch() not finding an element

data 826 9 8511 29

20 1 53 4

key 11

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

if (data[i] == key) {

}}

return -1;}

int i = 0

i < data.length ++i

i 0 1 2 3

i1 -1

4 5 6

Page 49: Arrays

52

How are we doing with How are we doing with searching?searching?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 50: Arrays

5353

SortingSorting

Page 51: Arrays

54

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 52: Arrays

55

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

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

20 1 53 4 76 98

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

20 1 53 4 76 98

Page 53: Arrays

56

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

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

20 1 53 4 76 98

Page 54: Arrays

57

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

20 1 53 4 76 98

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 2 Swaps third smallest element with v[2] This results in third smallest element being in the correct

place for a sorted result

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

20 1 53 4 76 98

Page 55: Arrays

58

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 3 Swaps fourth smallest element with v[3] This results in fourth smallest element being in the correct

place for a sorted result

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

20 1 53 4 76 98

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

20 1 53 4 76 98

Page 56: Arrays

59

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 4 Swaps fifth smallest element with v[4] This results in fifth smallest element being in the correct

place for a sorted result

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

20 1 53 4 76 98

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

20 1 53 4 76 98

Page 57: Arrays

60

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 58: Arrays

61

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 59: Arrays

62

How are we doing with How are we doing with sorting?sorting?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 60: Arrays

6363

New 2008 demotivatorsNew 2008 demotivators

Page 61: Arrays

6464

Binary searchBinary search

Page 62: Arrays

65

Binary search

Given a list, find a specific element in the list List MUST be sorted!

Each time it iterates through, it cuts the search space in half

A binary search is MUCH faster than a sequential search

Page 63: Arrays

66

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 64: Arrays

6767

Binary search use demo…Binary search use demo…

BSDemo.javaBSDemo.java

Page 65: Arrays

68

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

int i = 0; // left endpoint of search interval

int j = data.length-1; // right endpoint of search interval

while ( 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 66: Arrays

69

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 67: Arrays

70

Binary search But what if the element is not in the list?

Page 68: Arrays

71

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

7

Page 69: Arrays

72

How are we doing with How are we doing with binary search?binary search?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 70: Arrays

73

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

Page 71: Arrays

74

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 72: Arrays

75

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

Sequential search takes n iterations to find the element

Binary search takes 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 73: Arrays

76

How are we doing with How are we doing with binary search?binary search?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 74: Arrays

7878

Vector classVector class

Page 75: Arrays

79

Limitations of arrays You can’t change their size once created

This can be a big problem!

So we will create a new class that will operate like an array: We can store and get elements by index number It will automatically increase in size as needed And other fancy features…

Let’s call the class Vector As we are basically writing the java.util.Vector class

Page 76: Arrays

80

Properties of our Vector class

It needs to have an array to hold the values

As our internal array will often be bigger than the number of elements in the Vector, we need a size as well More on what this means in a slide or two…

Not much else…

Page 77: Arrays

81

Methods in our Vector class Insert and remove elements into the Vector Get an element from the Vector Find the length Print it out to the screen

What happens when the array field is full, and we want to add an element? We will need to increase the size of the array So we need a method to do that as well

Page 78: Arrays

82

Our first take on our Vector classpublic class Vector { private Object array[]; private int size = 0;

Vector() { array = new Object[100]; }

Vector(int length) { array = new Object[length]; }}

What does this mean? We’ll see that a bit later… But briefly, it means the array can store any object

Page 79: Arrays

83

Adding an element to our Vector

public void add (Object o) {array[size++] = o;

}

Pretty easy!

But what if the array is full?

We need a way to increase the capacity of the array

Page 80: Arrays

84

Increasing the Vector’s array’s capacity

private void increaseCapacity() {int oldSize = array.length;Object newArray[] = new Object[2*oldSize];for ( int i = 0; i < oldSize; i++ )

newArray[i] = array[i];array = newArray;

}

And our new add() method:

public void add (Object o) {if ( size == array.length )

increaseCapacity();array[size++] = o;

}

Page 81: Arrays

85

Methods can be private as well

Notice that the increaseCapacity() method is called only by the add() method when necessary

It’s not ever going to be called by whomever is using our Vector

Thus, we will make it private

That means that only other Vector methods can call it

Page 82: Arrays

86

Removing an element from a Vector

public Object remove (int which) {Object ret = array[which];for ( int i = which; i < array.length-1; i+

+ )array[i] = array[i+1];

array[array.length-1] = null;size--;return ret;

}

Page 83: Arrays

8787

Safety AwardsSafety Awards

safety_Awards_2006.ppssafety_Awards_2006.pps

Page 84: Arrays

88

Miscellaneous other methods

public int size() {return size;

}

public Object get (int which) {return array[which];

}

Page 85: Arrays

89

Our toString() method

public String toString() {String ret = "[";for ( int i = 0; i < size; i++ ) {

ret += array[i];if ( i != size-1 )

ret += ", ";}ret += "]";return ret;

}

Page 86: Arrays

90

Using our Vector This code is in a separate class called VectorUsage

public static void main (String[] args) {Vector v = new Vector();for ( int i = 12; i < 30; i++ ) {

v.add (String.valueOf(i));}System.out.println (v);System.out.println (v.size());String s = (String) v.get(5);System.out.println (s);v.remove (5);System.out.println (v);v.remove (5);System.out.println (v);

}

Page 87: Arrays

9191

Program DemoProgram Demo

VectorUsage.javaVectorUsage.java

Page 88: Arrays

92

The “real” Vector class Java provides a Vector class

In java.util

It contains all of the methods shown

Page 89: Arrays

9393

Program DemoProgram Demo

VectorUsage.javaVectorUsage.java But using java.util.VectorBut using java.util.Vector

Page 90: Arrays

94

What about those errors? When compiled with java.util.Vector, we see:

Note: C:\...\VectorUsage.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

You can ignore these They deal with generics (aka templates), which you will

see in future courses The program was still compiled

Page 91: Arrays

95

More on using the Vector class To add a String object s to the end of a Vector v

v.add(s);

To get the String object at the end of the Vector v String s = (String) v.get(v.size()-1);

To remove a String object from the end of a Vector v String s = (String) v.remove(v.size()-1); This both removes the object from the Vector and stores

the removed value into s

Page 92: Arrays

96

How are we doing with How are we doing with Vectors?Vectors?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 93: Arrays

9797

Stuff you don’t see Stuff you don’t see everyday…everyday…

StuffYouDontSeeEveryDay.ppsStuffYouDontSeeEveryDay.pps

Page 94: Arrays

9999

Multi-dimensional arraysMulti-dimensional arrays

Page 95: Arrays

100

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 96: Arrays

101

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!

m

m[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 97: Arrays

102

Example Alternative

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

Produces

m

m[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 98: Arrays

103

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 99: Arrays

104

Example Segment

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

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

}}

0

0

0

0

0

0

0

0

0

0

0

0

Page 100: Arrays

105

Rows by columns or columns by rows? Consider int[][] m = new int[3][4];

Is that 3 rows by 4 columns or 3 columns by 4 rows?

The answer is that it can be either As long as you are consistent with your column/row

placement

0 0 0

0 0 0

0 0 0

0 0 0

or

0 0 0

0 0 0

0 0 0 0

0

0

Page 101: Arrays

106

Rows by columns or columns by rows? This makes it 3 columns by 4 rows:

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

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

}

This makes it 3 rows by 4 columns:

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 102: Arrays

107

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 null

null 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 103: Arrays

108

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 104: Arrays

109109

FractalsFractals

Page 105: Arrays

110110

Fractal zoomingFractal zooming

http://www.fractalartcontests.com/20http://www.fractalartcontests.com/2000/en/entry-004-7.htm00/en/entry-004-7.htm

Page 106: Arrays

111

Explicit Initialization Segment

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

Produces

c

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

1 2

3 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 107: Arrays

112

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 a 1 2 a 1 n

a2 1 a 2 2 a 2 n

am 1 a m 2 a m n

Page 108: Arrays

113

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 109: Arrays

114

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 110: Arrays

115

Homework 10 You will be creating a Map class

The Map class contains a 2-D array In each spot will be a Location object

(from a previous HW) Lab 11 is (was?) going to be a MapPrinter class

Will print out the 2-D Map via text

Page 111: Arrays

116

How are we doing with 2-D How are we doing with 2-D arrays?arrays?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 112: Arrays

117117

Driving in BoliviaDriving in Bolivia

DrivingInBolivia.ppsDrivingInBolivia.pps

Page 113: Arrays

118118

Wrapper classesWrapper classes

Page 114: Arrays

119

But what about adding variables? The add method takes an Object as a parameter

public void add (Object o) { Although we haven’t seen it yet, this means you can add

any object you want to the vector

Primitive types (i.e. variables) are not objects How can they be added?

The solution: wrapper classes!

Page 115: Arrays

120

The Integer wrapper class This is how you add an int variable to a Vector:

int x = 5;Integer i = new Integer(x);vector.add (i);//…Integer j = (Integer) v.get(0);int y = j.intValue();

Pretty annoying syntax – we’ll see how to get around it in a bit…

Page 116: Arrays

121

More on wrapper classes

All the primitive types have wrapper classes Usually, the names are just the capitalized version of the

type I.e. Double for double, Byte for byte, etc.

Two exceptions: int and char int has Integer char has Character

Page 117: Arrays

122

More on wrapper classes Consider this code:

int x = 5;vector.add (x);//…int y = vector.get(0);

Does this code work? It shouldn’t

As we are adding a variable (not an object) to a vector But it does work!

Why?

Page 118: Arrays

123

Auto-boxing Java 1.5 will automatically “wrap” a primitive value into it’s

wrapper class when needed And automatically “unwrap” a wrapper object into the

primitive value

So Java translates the previous code into the following:

int x = 5;vector.add (new Integer(x));//…int y = ((Integer)vector.get(0)).intValue();

This is called autoboxing And auto-unboxing (unauto-boxing?) This does not work in Java 1.4 or before

Page 119: Arrays

124

More on auto-boxing Consider the following code:

Double d = 7.5;Double e = 6.5;Double f = d + e;System.println (f);

This is doing a lot of auto-boxing (and auto-unboxing):

Double d = new Double(7.5);Double e = new Double(6.5);Double f = newDouble(d.doubleValue() +

e.doubleValue());System.println (f);

Page 120: Arrays

125

How are we doing with How are we doing with Wrapper classes?Wrapper classes?

20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!

2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good

3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either

4.4. Not well. I’m Not well. I’m kinda confusedkinda confused

5.5. Not at all. I’m Not at all. I’m soooooo lost.soooooo lost.

Page 121: Arrays

126126

Star Wars Episode 3 TrailerStar Wars Episode 3 Trailer

Page 122: Arrays

127127

Star Wars Episode 3 TrailerStar Wars Episode 3 Trailer

That was a edited versionThat was a edited version– I changed the PG-rated trailer to a G-I changed the PG-rated trailer to a G-

rated trailerrated trailer

The original one can be found at The original one can be found at http://www.sequentialpictures.com/http://www.sequentialpictures.com/– Or Google for “star wars parody”Or Google for “star wars parody”