09 ch8 arrays

122
1  Arrays Chapter 8 Spring 2007 CS 101 Aaron Bloomfield

Upload: sourajit-mitra

Post on 03-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 1/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 2/122

22

Introduction to arraysIntroduction to arrays

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 3/122

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 4/122

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 5/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 6/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 7/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 8/122

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)

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 9/122

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) thecommon name

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 10/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 11/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 12/122

12

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 13/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 14/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 15/122

15

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 16/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 17/122

17

 Array members Member length

Size of the array

for (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()

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 18/122

1818

Chapter 2: Computer bugsChapter 2: Computer bugs

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 19/122

19

 Array members Member clone()

Produces a shallow copy

Point[] 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);

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 20/122

20

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]

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 21/122

21

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 

Example

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

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

}

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 22/122

22

Making a deep copy

Poi nt : ( 0, 0)

w

w[ 0] w[ 1]

Poi nt : ( 2, 1) Poi nt : ( 2, 2)

w[ 2]

u

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

Poi nt : ( 0, 0) Poi nt : ( 2, 1) Poi nt : ( 2, 2)

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 23/122

23

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 24/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 25/122

2525

TodayToday’ ’ ss demotivatorsdemotivators

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 26/122

26

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

    V  e  r  y   w  e

   l   l   !    T   h   i

  s   s   t  u   f   f    i

 . . .

    F  a   i  r   l  y 

  w  e   l   l 

  –   w   i   t   h

   a    l   i   t   t .

 .

   O   k  a

  y .    I   t   ’  s

   n  o   t

   g   r  e  a   t

 ,    b  u .

 . .

    N  o   t

   w  e   l   l .

    I   ’  m

    k   i  n

  d  a   c . . .

    N  o   t

   a   t   a

   l   l .    I   ’  m

   s  o  o

  o  o  o .

 . .

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

easy!easy!

2.2. Fairly wellFairly well –  –  with a little with a littlereview, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,

but itbut it’’s not horrible,s not horrible,eithereither

4.4. Not well. INot well. I’’mm kindakinda

confusedconfused5.5. Not at all. INot at all. I’’mm

soooooosoooooo lost.lost.

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 27/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 28/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 29/122

29

 ArrayTools.java – outlinepublic class ArrayTools {

// class constantprivate 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 screenpublic 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) { ...

}

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 30/122

30

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

}}

Consider

int[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 };

putList(score);

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 31/122

31

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 32/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 33/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 34/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 35/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 36/122

36

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

    V  e  r  y   w

  e   l   l   ! 

   T   h   i  s

   s   t  u   f   f    i . .

 .

    F  a   i  r   l  y

   w  e   l   l   –

   w   i   t   h

   a    l   i   t   t .

 .

   O   k  a

  y .    I   t   ’  s

   n  o   t

   g   r  e  a   t

 ,    b  u .

 . .

    N  o   t   w  e

   l   l .    I   ’  m

    k   i  n

  d  a   c . . .

    N  o   t   a   t 

  a   l   l . 

   I   ’  m   s  o  o

  o  o  o .

 . .

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

easy!easy!

2.2. Fairly wellFairly well –  –  with a little with a littlereview, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,

but itbut it’’s not horrible,s not horrible,eithereither

4.4. Not well. INot well. I’’mm kindakinda

confusedconfused5.5. Not at all. INot at all. I’’mm

soooooosoooooo lost.lost.

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 37/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 38/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 39/122

39

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] + "'");

}

}}

P DP D

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 40/122

4040

Program DemoProgram Demo

MainParameters.javaMainParameters.java

ViaVia JCreator JCreator Via the command lineVia the command line

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 41/122

4141

Basic array searchingBasic array searching

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 42/122

42

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.lengthi = 0

Searching for a value

dat a 54 9

20 1

key 5

i -

dat a 54 9

20 1

key 5

i 0

dat a 54 9

20 1

key 5

i 0

dat a 54 9

20 1

key 5

i 0

dat a 54 9

20 1

key 5

i 1

dat a 54 9

20 1

key 5

i 1

dat a 54 9

20 1

key 5

i 1

dat a 54 9

20 1

key 5

i 2

dat a 54 9

20 1

key 5

i 2

dat a 54 9

20 1

key 5

i 2

dat a 54 9

20 1

key 5

i 2

dat a 54 9

20 1

key 5

i 2

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 43/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 44/122

H d i i h hi ?H d i ith hi ?

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 45/122

45

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

    V  e  r  y   w

  e   l   l   ! 

   T   h   i  s

   s   t  u   f   f    i . .

 .

    F  a   i  r   l  y

   w  e   l   l   –

   w   i   t   h

   a    l   i   t   t .

 .

   O   k  a

  y .    I   t   ’

  s   n  o   t   g 

  r  e  a   t

 ,    b  u .

 . .

    N  o   t   w

  e   l   l . 

   I   ’  m    k   i  n

  d  a   c . . .

    N  o   t   a   t

   a   l   l .

    I   ’  m

   s  o  o

  o  o  o .

 . .

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

easy!easy!

2.2. Fairly wellFairly well –  –  with a little with a littlereview, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,

but itbut it’’s not horrible,s not horrible,eithereither

4.4. Not well. INot well. I’’mm kindakinda

confusedconfused5.5. Not at all. INot at all. I’’mm

soooooosoooooo lost.lost.

FollowFollow--up on Knut the polar bearup on Knut the polar bear

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 47/122

47

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

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

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

}

}return -1;

}

Consider

int[] 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 0123

i1 3

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 48/122

48

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

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

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

}

}return -1;

}

Consider

int[] 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 0123

i1 -1

456

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 49/122

49

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

    V  e  r  y   w

  e   l   l   ! 

   T   h   i  s

   s   t  u   f   f    i . .

 .

    F  a   i  r   l

  y   w  e

   l   l   –   w   i   t   h

   a    l   i   t   t .

 .

   O   k  a  y . 

   I   t   ’  s   n  o   t   g 

  r  e  a   t

 ,    b  u .

 . .

    N  o   t   w

  e   l   l . 

   I   ’  m    k   i  n

  d  a   c . . .

    N  o   t   a   t

   a   l   l .

    I   ’  m

   s  o  o

  o  o  o .

 . .

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

easy!easy!

2.2. Fairly wellFairly well –  –  with a little with a littlereview, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,

but itbut it’’s not horrible,s not horrible,eithereither

4.4. Not well. INot well. I’’mm kindakinda

confusedconfused5.5. Not at all. INot at all. I’’mm

soooooosoooooo lost.lost.

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 50/122

5050

SortingSorting

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 51/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 52/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 53/122

l

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 54/122

54

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 correctplace for a sorted result

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

20 1 53 4 76 98

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 55/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 56/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 57/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 58/122

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 59/122

59

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

    V  e  r  y 

  w  e   l   l   !

    T   h   i

  s   s   t  u   f   f    i

 . . .

    F  a   i  r   l  y

   w  e   l   l   –

   w   i   t   h

   a    l   i   t   t .

 .

   O   k  a  y .

    I   t   ’  s

   n  o   t

   g   r  e  a   t

 ,    b  u .

 . .

    N  o   t   w

  e   l   l . 

   I   ’  m    k   i  n

  d  a   c . . .

    N  o   t   a

   t   a   l   l .

    I   ’  m

   s  o  o

  o  o  o .

 . .

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

easy!easy!

2.2. Fairly wellFairly well –  –  with a little with a littlereview, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,

but itbut it’’s not horrible,s not horrible,eithereither

4.4. Not well. INot well. I’’mm kindakinda

confusedconfused5.5. Not at all. INot at all. I’’mmsoooooosoooooo lost.lost.

New 2008New 2008 demotivatorsdemotivators

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 60/122

6060

New 2008New 2008 demotivatorsdemotivators

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 61/122

Binary search

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 62/122

62

Binary search

Given a list, find a specific element in the list

List MUST be sorted!

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

A binary search is MUCH faster than a sequentialsearch

Binary search use

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 63/122

63

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

}}

Binary search use demoBinary search use demo……

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 64/122

6464

yy

BSDemo.javaBSDemo.java

Binary search

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 65/122

65

Binary search

public 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;

}}

Binary search take 1

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 66/122

66

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 j m

0

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

key  14

945 7 76 656

returns:

6

data

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 67/122

Binary search take 2

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 68/122

68

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 j m

0

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

key  15

945 7 76

returns:

-1

data

7

How are we doing with binaryHow are we doing with binary

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 69/122

69

search?search?

    V  e  r  y

   w  e   l   l   ! 

   T   h   i  s

   s   t  u   f   f    i . .

 .

    F  a   i  r   l  y

   w  e   l   l   –

   w   i   t   h

   a    l   i   t   t .

 .

   O   k  a  y

 .    I   t   ’

  s   n  o   t   g 

  r  e  a   t

 ,    b  u .

 . .

    N  o   t   w  e   l   l .

    I   ’  m

    k   i  n

  d  a   c . . .

    N  o   t   a

   t   a   l   l .

    I   ’  m

   s  o  o

  o  o  o .

 . .

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

easy!easy!

2.2. Fairly wellFairly well –  –  with a little with a littlereview, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,

but itbut it’’s not horrible,s not horrible,eithereither

4.4. Not well. INot well. I’’mm kindakindaconfusedconfused

5.5. Not at all. INot at all. I’’mmsoooooosoooooo lost.lost.

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 70/122

How long does a binary search take?

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 71/122

71

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 72/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 73/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 74/122

Limitations of arrays

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 75/122

75

y

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 76/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 77/122

Our first take on our Vector class

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 78/122

78

public 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

 Adding an element to our Vector

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 79/122

79

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 80/122

Methods can be private as well

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 81/122

81

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

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

Thus, we will make it private

That means that only other Vector methods can call it

Removing an element from a Vector

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 82/122

82

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;

}

Safety AwardsSafety Awards

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 83/122

8383

safety_Awards_2006.ppssafety_Awards_2006.pps

Miscellaneous other methods

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 84/122

84

public int size() {

return size;}

public Object get (int which) {

return array[which];

}

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 85/122

Using our Vector

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 86/122

86

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

}

Program DemoProgram Demo

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 87/122

8787

VectorUsage.javaVectorUsage.java

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 88/122

Program DemoProgram Demo

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 89/122

8989

VectorUsage.javaVectorUsage.java

But usingBut using java.util.Vector java.util.Vector

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 90/122

More on using the Vector class

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 91/122

91

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

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 92/122

92

    V  e  r  y   w  e   l   l   !

    T   h   i

  s   s   t  u   f   f    i

 . . .

    F  a   i  r   l

  y   w  e

   l   l   –   w   i   t   h

   a    l   i   t   t .

 .

   O   k  a  y .

    I   t   ’  s

   n  o   t

   g   r  e  a   t

 ,    b  u .

 . .

    N  o   t   w

  e   l   l . 

   I   ’  m    k   i  n

  d  a   c . . .

    N  o   t   a   t   a

   l   l .    I   ’  m

   s  o  o

  o  o  o .

 . .

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

easy!easy!

2.2. Fairly wellFairly well –  –  with a little with a littlereview, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,

but itbut it

’’s not horrible,s not horrible,

eithereither

4.4. Not well. INot well. I’’mm kindakindaconfusedconfused

5.5. Not at all. INot at all. I’’mmsoooooosoooooo lost.lost.

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 93/122

9393

StuffYouDontSeeEveryDay.ppsStuffYouDontSeeEveryDay.pps

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 94/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 95/122

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 96/122

Example

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 97/122

97

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]

Multidimensional array visualization

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 98/122

98

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

Example

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 99/122

99

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

Rows by columns or columns by rows?

d i [][] i [ ][ ]

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 100/122

100

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/rowplacement

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

Rows by columns or columns by rows?

Thi k it 3 l b 4

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 101/122

101

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();

}

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 102/122

Multidimensional array visualization

Segment

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 103/122

103

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 104/122

Fractal zoomingFractal zooming

htt // f t l t t t /2000/htt // f t l t t t /2000/

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 106/122

106

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]

Matrices

A two-dimensional array is sometimes known as a matrix

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 107/122

107

A two dimensional array is sometimes known as a matrixbecause it resembles that mathematical concept

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

a1 1, a1 2, … a1 n,

a2 1, a2 2, … a2 n,

…   …

am 1, am 2, … am n,

Matrix addition

Definition C = A + B

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 108/122

108

Definition C = A + B

cij = aij + bij

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

A and B

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 109/122

Homework 10

You will be creating a Map class

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 110/122

110

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

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

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

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 111/122

111    V  e  r  y

   w  e   l   l   ! 

   T   h   i  s

   s   t  u   f   f    i . . .

    F  a   i  r   l  y

   w  e   l   l   –

   w   i   t   h

   a    l   i   t   t . .

   O   k  a  y

 .    I   t   ’

  s   n  o   t   g 

  r  e  a   t

 ,    b  u . . .

    N  o

   t   w  e   l   l . 

   I   ’  m    k   i  n

  d  a   c . . .

    N  o

   t   a   t   a

   l   l .    I   ’  m

   s  o  o

  o  o  o . . .

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

easy!easy!

2.2.

Fairly wellFairly well –  –  with a little with a littlereview, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,but itbut it’’s not horrible,s not horrible,eithereither

4.4. Not well. INot well. I’’mm kindakindaconfusedconfused

5.5. Not at all. INot at all. I’’mmsoooooosoooooo lost.lost.

Driving in BoliviaDriving in Bolivia

DrivingInBolivia ppsDrivingInBolivia pps

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 112/122

112112

DrivingInBolivia.ppsDrivingInBolivia.pps

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 113/122

113113

Wrapper classesWrapper classes

But what about adding variables?

The add method takes an Object as a parameter

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 114/122

114

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!

The Integer wrapper class

This is how you add an int variable to a Vector:

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 115/122

115

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 abit…

More on wrapper classes

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 116/122

116

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

More on wrapper classes

Consider this code:

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 117/122

117

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?

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 118/122

More on auto-boxing

Consider the following code:

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 119/122

119

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

How are we doing withHow are we doing with

 Wrapper classes? Wrapper classes?

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

!!

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 120/122

120    V  e

  r  y   w  e   l   l   ! 

   T   h   i  s

   s   t  u   f   f    i . . .

    F

  a   i  r   l  y

   w  e   l   l   –

   w   i   t   h

   a    l   i   t   t . .

   O   k

  a  y .    I   t   ’

  s   n  o   t   g 

  r  e  a   t

 ,    b  u . . .

    N  o   t

   w  e   l   l . 

   I   ’  m    k   i  n

  d  a   c . . .

    N  o   t

   a   t   a

   l   l .    I   ’  m

   s  o  o

  o  o  o . . .

easy!easy!

2.2.

Fairly wellFairly well

 –  – 

 with a little with a little

review, Ireview, I’’ll be goodll be good

3.3. Okay. ItOkay. It’’s not great,s not great,but itbut it’’s not horrible,s not horrible,

eithereither4.4. Not well. INot well. I’’mm kindakinda

confusedconfused

5.5. Not at all. INot at all. I’’mmsoooooosoooooo lost.lost.

Star Wars Episode 3 TrailerStar Wars Episode 3 Trailer

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 121/122

121121

Star Wars Episode 3 TrailerStar Wars Episode 3 Trailer

That was a edited versionThat was a edited version

7/29/2019 09 Ch8 Arrays

http://slidepdf.com/reader/full/09-ch8-arrays 122/122

122122

 – – I changed the PGI changed the PG--rated trailer to a Grated trailer to a G--ratedrated

trailertrailer

The original one can be found atThe original one can be found athttp://http://www.sequentialpictures.comwww.sequentialpictures.com / /

 – – Or Google forOr Google for “ “star wars parodystar wars parody” ”