cs 106a, lecture 16 arrays - stanford university · 2017-07-26 · 7 why are data structures...

46
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others. CS 106A, Lecture 16 Arrays suggested reading: Java Ch. 11.1-11.5

Upload: dinhkhanh

Post on 03-Jul-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

CS106A,Lecture16Arrays

suggestedreading:JavaCh.11.1-11.5

Page 2: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

2

Where Are We in CS 106A?•KareltheRobot•Java•ConsolePrograms•TextProcessing•GraphicsPrograms•DataStructures•DefiningourownVariableTypes•GUIs

Page 3: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

3

Midterm!Arrays

HW5:ImageShop

Youarehere

Page 4: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

4

Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap

Page 5: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

5

Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap

Page 6: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

6

What are Data Structures?

Datastructuresarevariabletypesthatcanstoredataininteresting

ways.

Page 7: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

7

Why Are Data Structures Useful?ConsideraprogramsimilartoWeatherfromHW2thatpromptsfordailytemperaturesandprintsaverages,high/lows,etc.

– Whyisthishardtowritewithwhatwe'velearnedsofar?

How many days' temperatures? 7Day 1's high temp: 45Day 2's high temp: 44Day 3's high temp: 39Day 4's high temp: 48Day 5's high temp: 37Day 6's high temp: 46Day 7's high temp: 53All temperatures: [45, 44, 39, 48, 37, 46, 53]Average temp = 44.64 days were above average.Two coldest days: 37, 39Two hottest days: 53, 48

Page 8: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

8

Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap

Page 9: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

9

ArraysAnewvariabletypethatisanobjectthatrepresentsanordered,homogeneouslist ofdata.

– Arrayshavemanyelements thatyoucanaccessusingindices

index 0 1 2 3 4 5 6 7 8 9

value 12 49 -2 26 5 17 -6 84 72 3

element0 element4 element9

length=10

Page 10: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

10

Creating an Arraytype[] name = new type[length];

int[] numbers = new int[5];

index 0 1 2 3 4value 0 0 0 0 0

Javaautomaticallyinitializeselementsto0.

Page 11: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

11

Accessing Data In An Array

name[index] // get element at index

• LikeStrings,indicesgofrom0 tothearray'slength- 1.for (int i = 0; i < 7; i++) {

println(numbers[i]);}println(numbers[9]); // exceptionprintln(numbers[-1]); // exception

index 0 1 2 3 4 5 6value 0 1 2 3 4 5 6

Page 12: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

12

Putting Data In An Array

name[index] = value; // set element at index

Page 13: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

13

Putting Data In An Array

name[index] = value; // set element at index

• LikeStrings,indicesgofrom0 tothearray'slength- 1.int[] numbers = new int[7];for (int i = 0; i < 7; i++) {

numbers[i] = i;}numbers[8] = 2; // exceptionnumbers[-1] = 5; // exception

index 0 1 2 3 4 5 6value 0 1 2 3 4 5 6

Page 14: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

14

PracticeQ:Whatarethecontentsofnumbers afterexecutingthiscode?

int[] numbers = new int[8];numbers[1] = 3;numbers[4] = 7;numbers[6] = 5;int x = numbers[1];numbers[x] = 2;numbers[numbers[4]] = 9;

// 0 1 2 3 4 5 6 7A. {0, 3, 0, 2, 7, 0, 5, 9}B. {0, 3, 0, 0, 7, 0, 5, 0}C. {3, 3, 5, 2, 7, 4, 5, 0}D. {0, 3, 0, 2, 7, 6, 4, 4}

arrayElements1

Page 15: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

15

Arrays Of Other TypesYoucancreatearraysofanyvariabletype.Forexample:

double[] results = new double[5];

String[] names = new String[3];

boolean[] switches = new boolean[4];

GRect[] rects = new GRect[5];

• Javainitializeseachelementofanewarraytoitsdefaultvalue,whichis0 forint anddouble,‘\0’ forchar,false forboolean,andnull forobjects.

Page 16: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

16

Array LengthSimilartoaString,youcangetthelengthofanarraybysaying

myArray.length

Notethattherearenoparenthesesattheend!

Practice:•Whatistheindexofthelastelement ofanarrayintermsofitslength?

•Whatistheindexofthemiddleelement ofanarrayintermsofitslength?

Page 17: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

17

Arrays + For Loops = ❤JustlikewithStrings,wecanuseanarray’slength,alongwithitsindices,toperformcooloperations.

Page 18: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

18

Arrays + For Loops = ❤JustlikewithStrings,wecanuseanarray’slength,alongwithitsindices,toperformcooloperations.Forinstance,wecanefficientlyinitializearrays.

int[] numbers = new int[8];for (int i = 0; i < numbers.length; i++) {

numbers[i] = 2 * i;}

index 0 1 2 3 4 5 6 7

value 0 2 4 6 8 10 12 14

Page 19: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

19

Arrays + For Loops = ❤JustlikewithStrings,wecanuseanarray’slength,alongwithitsindices,toperformcooloperations.Forinstance,wecanreadinnumbersfromtheuser:

int length = readInt("# of numbers? ");int[] numbers = new int[length];for (int i = 0; i < numbers.length; i++) {

numbers[i] = readInt("Elem " + i + ": ");}

Page 20: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

20

Arrays + For Loops = ❤JustlikewithStrings,wecanuseanarray’slength,alongwithitsindices,toperformcooloperations.Forinstance,wecansumup allofanarray’selements.

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

sum += numbers[i];}println(sum);

Page 21: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

21

Brief Aside: Creating ArraysSometimes,wewanttohardcodetheelementsofanarray.

int numbers = new int[7];numbers[0] = 5;numbers[1] = 32;numbers[3] = 12;...

// This is tedious!

Page 22: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

22

Brief Aside: Creating ArraysSometimes,wewanttohardcodetheelementsofanarray.Luckily,Javahasaspecialsyntaxforinitializingarraystohardcodednumbers.

type[] name = { elements };

// Java infers the array lengthint[] numbers = {5, 32, 12, 2, 1, -1, 9};

Page 23: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

23

Limitations of Arrays• Anarray’slengthisfixed.Youcannotresizeanexistingarray:int[] a = new int[4];a.length = 10; // error

• Youcannotcomparearrayswith== orequals :int[] a1 = {42, -7, 1, 15};int[] a2 = {42, -7, 1, 15};if (a1 == a2) { ... } // false!if (a1.equals(a2)) { ... } // false!

• Anarraydoesnotknowhowtoprintitself:println(a1); // [I@98f8c4]

Page 24: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

24

Arrays Methods To The Rescue!• TheclassArrays inpackagejava.util hasusefulmethodsformanipulatingarrays:

Methodname DescriptionArrays.binarySearch(array, value) returnstheindexofthegivenvalueinasorted

array(or<0ifnotfound)Arrays.copyOf(array, length) returnsanewcopyofarrayofgivenlengthArrays.equals(array1, array2) returnstrue ifthetwoarrayscontainsame

elementsinthesameorderArrays.fill(array, value); setseveryelementtothegivenvalueArrays.sort(array); arrangestheelementsintosortedorderArrays.toString(array) returnsastringrepresentingthearray,suchas

"[10, 30, -25, 17]"

Page 25: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

25

Example: Arrays.toStringArrays.toString acceptsanarrayasaparameterandreturnsastringrepresentationofitselements.

int[] e = {0, 2, 4, 6, 8};e[1] = e[3] + e[4]; println("e is " + Arrays.toString(e));

Output:e is [0, 14, 4, 6, 8]

Page 26: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

26

Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap

Page 27: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

27

Passing Arrays Between Methods

•Arraysarejustanothervariabletype,somethodscantakearraysasparametersandreturnanarray.

private int sumArray(int[] numbers) {...

}

private int[] makeSpecialArray(...) {...return myArray;

}

Page 28: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

28

Passing Arrays Between Methods

•Arraysarejustanothervariabletype,somethodscantakearraysasparametersandreturnanarray.

•However,arraysareobjects,soperAVariableOriginStory,anarrayvariableboxactuallystoresitslocation.

• Thismeanschangestoanarraypassedasaparameteraffecttheoriginalarray!

Page 29: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

29

Arrays: Pass By Referencepublic void run() {

int[] numbers = new int[7];fillArray(numbers);println(Arrays.toString(numbers));

}

private void fillArray(int[] arr) {for (int i = 0; i < arr.length; i++) {

arr[i] = 2 * i;}

}

Page 30: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

30

Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap

Page 31: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

31

Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap

Page 32: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

32

Practice: Swapping ElementsLet’swriteamethodcalledswapElements thatswapstwoelementsofanarray.Howcanwedothis?

Whatparametersshouldittake(ifany)?Whatshoulditreturn(ifanything)?

private ??? swapElements(???) {...

}

Page 33: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

33

Swap: Take 1public void run() {

int[] array = new int[5];...swapElements(array[0], array[1]);...

}

private void swapElements(int x, int y) {int temp = x;x = y;y = temp;

}

Page 34: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

34

Swap: Take 1public void run() {

int[] array = new int[5];...swapElements(array[0], array[1]);...

}

private void swapElements(int x, int y) {int temp = x;x = y;y = temp;

}

Ints areprimitives,sotheyarepassedbyvalue!Theirvariableboxesstoretheiractualvalues.Sochangestotheparameterdonotaffecttheoriginal.

Page 35: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

35

Swap: Take 2public void run() {

int[] array = new int[5];...swapElements(array, 0, 1);...

}

private void swapElements(int[] arr, int pos1, int pos2) {int temp = arr[pos1];arr[pos1] = arr[pos2];arr[pos2] = temp;

}

Page 36: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

36

Swap: Take 2public void run() {

int[] array = new int[5];...swapElements(array, 0, 1);...

}

private void swapElements(int[] arr, int pos1, int pos2) {int temp = arr[pos1];arr[pos1] = arr[pos2];arr[pos2] = temp;

}

Arraysareobjects,sotheyarepassedbyreference!Theirvariableboxesstoretheirlocation.Sochangestotheparameterdoaffecttheoriginal.

Page 37: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

37

Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap

Page 38: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

38

WeatherStation• WriteaWeatherStation programthatpromptstheusertoenterdailytemperatures,andusesanarraytoproducethisoutput:

How many days' temperatures? 7Day 1's high temp: 45Day 2's high temp: 44Day 3's high temp: 39Day 4's high temp: 48Day 5's high temp: 37Day 6's high temp: 46Day 7's high temp: 53

All temperatures: [45, 44, 39, 48, 37, 46, 53]Average temp = 44.64 days were above average.Two coldest days: 37, 39Two hottest days: 53, 48

Weather

Page 39: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

39

Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap

Page 40: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

40

Recap: Arrays•Anarrayisanordered,homogeneouslist ofdata.• Arrayscanstorebothprimitivesandobjects•Anarray’slengthcannotbechanged onceitiscreated.• Therearenomethodsyoucancallonanarray;however,thereisthehelpfulArrays class,withmethodssuchasArrays.toString.

Page 41: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

41

Recap•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation

Nexttime:2DArrays

Page 42: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

ExtraSlides

Page 43: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

43

Array reverse exercise• Writeareversemethodthatreversestheelementsofanarray.

– Example:int[] numbers = {11, 42, -5, 27, 0, 89};reverse(numbers);

– Afterthecall,itshouldstore:[89, 0, 27, -5, 42, 11]

– Thecodeshouldworkforanarrayofanysize.

Page 44: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

44

Algorithm idea• Swappairsofelementsfromtheedges;workinwards:

index 0 1 2 3 4 5value 11 42 -5 27 0 89index 0 1 2 3 4 5value 89 42 -5 27 0 11index 0 1 2 3 4 5value 89 0 -5 27 42 11index 0 1 2 3 4 5value 89 0 27 -5 42 11

Page 45: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

45

Possible algorithm• Q:Whatistheeffectofthecodebelow?Doesitreversethearray?int[] numbers = {11, 42, -5, 27, 0, 89};// reverse the arrayfor (int i = 0; i < numbers.length; i++) {

int temp = numbers[i];numbers[i] = numbers[numbers.length - 1 - i];numbers[numbers.length - 1 - i] = temp;

}

– A. Codeiscorrectandreversesthearrayproperly.– B. Elementsarereversed,butsomearelost/missing.– C. Indexesareoff-by-1.– D. Arraycontentsarethesameattheend;thecodedoesnothing.– E. Noneoftheabove

Page 46: CS 106A, Lecture 16 Arrays - Stanford University · 2017-07-26 · 7 Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures

46

Correct algorithm• Correctedversion:int[] numbers = {11, 42, -5, 27, 0, 89};// reverse the arrayfor (int i = 0; i < numbers.length / 2; i++) {

int temp = numbers[i];numbers[i] = numbers[numbers.length - 1 - i];numbers[numbers.length - 1 - i] = temp;

}

index 0 1 2 3 4 5value 11 42 -5 27 0 89index 0 1 2 3 4 5value 89 42 -5 27 0 11index 0 1 2 3 4 5value 89 0 -5 27 42 11index 0 1 2 3 4 5value 89 0 27 -5 42 11