Docsity

Array Manipulation and Data Management in Java, Study notes of Computer Science

Partial preview of the text

Download Array Manipulation and Data Management in Java and more Study notes Computer Science in PDF only on Docsity!

Java:Learning to Program with RobotsChapter 10: Arrays

Chapter Objectives

After studying this chapter, you should be able to:

Store data in an array, access a single element, process allelements, search for a particular element, and put the elements inorder

Declare, allocate, and initialize an array

Handle changing numbers of elements in an array, includinginserting a new element and deleting an existing one

Enlarge or shrink the size of an array

Manipulate data stored in a multi-dimensional array

10.1: Using Arrays (2/2)

Wanted:

A way to easily work with 1,500 (or many more!) persons collectedfrom

www.myspace.com

Each person represented as an instance of the

Person

class:

Person

-String name-int id-Gender gender-int age-String city-String province-String country-DateTime lastLogon-??? friends+Person(Scanner in)+String getName( )+int getID( )+Gender getGender( )...

10.1.1: Visualizing An Array

Person[ ] length

[0] [1] [2] [3] [4] [5] [6] [7]

perso ns

Steve,

MALE, 16,

St.

Cat

Ken,

MALE, 18,

Niagara-on

Beth, FEMALE, 17, St.

Cat

Kathleen,

FEMALE, 23, Tim

Roydyn, MALE, 21, Fonth

Kala,

FEMALE,

18, Niaga

Ali, MALE,

Boston, MS

Zaki, FEMALE, 21,

Kitch

10.1.3: Swapping Array Elements (1/2)

public class PersonList extends Object{ … persons …

/** Swap the person object at index a with the object at index b. */ public void swap(int a, int b){ Person temp = this.persons[a];

this.persons[a] = this.persons[b];this.persons[b] = temp; }

} Assume that

swap(1, 2)

has been called.

Person temp = this.persons[a];

Person[ ] length

4

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

perso ns

Steve,

MALE, 16,

St.

Cat

Ken,

MALE, 18,

Niagara-on

Beth,

FEMALE, 17, St. Cat

Kathleen,

FEMALE, 23,

Tim

temp

(trace continued on next slide)

10.1.3: Swapping Array Elements (2/2)

this.persons[a] = this.persons[b];

Person[ ] length

4

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

perso ns

Steve,

MALE, 16,

St.

Cat

Ken,

MALE, 18,

Niagara-on

Beth,

FEMALE, 17, St. Cat

Kathleen,

FEMALE, 23,

Tim

temp

this.persons[b] = temp;

Person[ ] length

4

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

perso ns

Steve,

MALE, 16,

St.

Cat

Ken,

MALE, 18,

Niagara-on

Beth,

FEMALE, 17, St. Cat

Kathleen,

FEMALE, 23,

Tim

temp

// After the swap method finishes

Person[ ] length

4

[0] [1] [2]

perso ns

Steve,

MALE, 16,

St.

Cat

Ken,

MALE, 18,

Niagara-on

Beth,

FEMALE, 17, St. Cat

10.1.4: Processing All Elements with ForEach

public class PersonList extends Object{ … persons …

/** Calculate the average number of friends */ public double calcAverageNumberOfFriends(){ int sumFriends = 0;

for( int i = 0; i < this.persons.length; i += 1){ Person p = this.persons[i];

sumFriends = sumFriends + p.getNumFriends(); } return (double) sumFriends / this.persons.length; } /** Calculate the average number of friends using a “foreach loop” */ public double calcAverageNumberOfFriends(){ int sumFriends = 0;

for( Person p : this.persons ){ sumFriends = sumFriends + p.getNumFriends();} return (double) sumFriends / this.persons.length; } }

10.1.5: Processing Matching Elements

for (

each element in the array

{ if (

the element meets some criteria

{^

process the element } } public class PersonList extends Object{ … persons …

/** Count the number of minors (persons less than 18 years old). */ public int countMinors(){ int count = 0;

for(int i = 0; i < this.persons.length; i += 1){ if (this.persons[i].getAge() < 18)

{ count += 1;} } return count; } }

10.1.6: Searching (2/2)

One way of structuring the search is to ask when we’re done:

Found the correct element (success!)

Reached the end of the list (failure)

public class PersonList extends Object{ … persons …

/** Find the person with the given id; null if not found. Use a traditional loop */ public Person search2(int id){ int i = 0;

while (i < this.persons.length && this.persons[i].getID() != id){ i += 1;} Person answer = null;if (i < this.persons.length){ answer = this.persons[i];} return answer; } }

10.1.7: Finding an Extreme Element (1/2)

An extreme element has the most of something or the least ofsomething. The most age, the longest time since the last login, the“smallest” name (first in dictionary order), etc. remember the first element as the best seen so far for (

each remaining element in the array

{ if (

the current element is better than the best seen so far

{^

remember the current element as the best seen so far } } return

best element seen so far

10.1.8: Sorting an Array (Ideas 1/3)

Sorting an array puts all the elements in order by age, name, or someother criteria.Selection Sort is one of many algorithms to sort an array. It builds onthree patterns we’ve already seen:

Process All Elements

Find an Extreme

Swap Two Elements

We’ll sort the

persons

array by name.

Person[ ] length

7

[0] [1] [2] [3] [4] [5] [6]

perso ns

F aizel,

MALE,

16,

St.

Ca

D oug,

MALE,

18,

Niagara-

B e

th,

FEMALE,

17,

St.

C athy,

FEMALE,

23,

Tim

G reg,

MALE,

21,

Fonth

E llen, FEMALE, 18, Niaga A li,

MALE,

19,

Boston,

F

E

A

G

B

D

C

Person[ ] length

7

[0] [1] [2] [3] [4] [5] [6]

perso ns

F aizel,

MALE,

16,

St.

Cat

D o

ug,

MALE,

18,

Niagara-on

B e

th,

FEMALE,

17,

St.

C

C athy,

FEMALE,

23,

Tim

G reg,

MALE,

21,

Fonth

E llen, FEMALE, 18, Niaga A l

i, MALE,

19,

Boston, MS

A

B

C

D

E

F

G

10.1.8: Sorting an Array (Ideas 2/3)

Divide the array into the part that’s already sorted (dark background)and the part that isn’t (light background).

A

B

C

G

E

D

F

Repeatedly extend the sorted part of the array by:

Finding the smallest element in the unsorted part of the array.

A

B

C

G

E

D

F

Swapping it with the first element in the unsorted part of the array.

A

B

C

D

E

G

F

Extending the sorted part of the array.

A

B

C

D

E

G

F

10.1.8: Sorting an Array (Code 1/2)

public class PersonList extends Object{ … persons …

/** Sort the list of persons in alphabetical order by name. */^ public void sort(){ for (int firstUnsorted=0; firstUnsorted<this.persons.length-1;

firstUnsorted++)

{ int extremeIndex = this.findExtreme(firstUnsorted);

this.swap(firstUnsorted, extremeIndex); } } /** Swap the elements at indices a and b. */ private void swap(int a, int b){ Person temp = this.persons[a];

this.persons[a] = this.persons[b];this.persons[b] = temp; }

10.1.8: Sorting an Array (Code 2/2)

/** Find the extreme element in the unsorted portion of the array.* @param indexToStart the smallest index in the unsorted portion of the array */ private int findExtreme(int indexToStart){ int indexBestSoFar = indexToStart;

String nameBestSoFar = this.persons[indexBestSoFar].getName();for (int i=indexToStart+1; i<this.persons.length; i++){ String currPersonName = this.persons[i].getName();

if (currPersonName.compareTo(nameBestSoFar) < 0){ indexBestSoFar = i;

nameBestSoFar = this.persons[i].getName(); } } return indexBestSoFar; } }