cs 106a, lecture 16 arrays - stanford university · 2017-07-26 · 7 why are data structures...
TRANSCRIPT
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture16Arrays
suggestedreading:JavaCh.11.1-11.5
2
Where Are We in CS 106A?•KareltheRobot•Java•ConsolePrograms•TextProcessing•GraphicsPrograms•DataStructures•DefiningourownVariableTypes•GUIs
3
Midterm!Arrays
HW5:ImageShop
Youarehere
4
Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap
5
Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap
6
What are Data Structures?
Datastructuresarevariabletypesthatcanstoredataininteresting
ways.
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
8
Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap
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
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.
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
12
Putting Data In An Array
name[index] = value; // set element at index
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
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
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.
16
Array LengthSimilartoaString,youcangetthelengthofanarraybysaying
myArray.length
Notethattherearenoparenthesesattheend!
Practice:•Whatistheindexofthelastelement ofanarrayintermsofitslength?
•Whatistheindexofthemiddleelement ofanarrayintermsofitslength?
17
Arrays + For Loops = ❤JustlikewithStrings,wecanuseanarray’slength,alongwithitsindices,toperformcooloperations.
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
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 + ": ");}
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);
21
Brief Aside: Creating ArraysSometimes,wewanttohardcodetheelementsofanarray.
int numbers = new int[7];numbers[0] = 5;numbers[1] = 32;numbers[3] = 12;...
// This is tedious!
22
Brief Aside: Creating ArraysSometimes,wewanttohardcodetheelementsofanarray.Luckily,Javahasaspecialsyntaxforinitializingarraystohardcodednumbers.
type[] name = { elements };
// Java infers the array lengthint[] numbers = {5, 32, 12, 2, 1, -1, 9};
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]
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]"
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]
26
Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap
27
Passing Arrays Between Methods
•Arraysarejustanothervariabletype,somethodscantakearraysasparametersandreturnanarray.
private int sumArray(int[] numbers) {...
}
private int[] makeSpecialArray(...) {...return myArray;
}
28
Passing Arrays Between Methods
•Arraysarejustanothervariabletype,somethodscantakearraysasparametersandreturnanarray.
•However,arraysareobjects,soperAVariableOriginStory,anarrayvariableboxactuallystoresitslocation.
• Thismeanschangestoanarraypassedasaparameteraffecttheoriginalarray!
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;}
}
30
Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap
31
Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap
32
Practice: Swapping ElementsLet’swriteamethodcalledswapElements thatswapstwoelementsofanarray.Howcanwedothis?
Whatparametersshouldittake(ifany)?Whatshoulditreturn(ifanything)?
private ??? swapElements(???) {...
}
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;
}
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.
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;
}
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.
37
Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap
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
39
Plan for Today•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation•Recap
40
Recap: Arrays•Anarrayisanordered,homogeneouslist ofdata.• Arrayscanstorebothprimitivesandobjects•Anarray’slengthcannotbechanged onceitiscreated.• Therearenomethodsyoucancallonanarray;however,thereisthehelpfulArrays class,withmethodssuchasArrays.toString.
41
Recap•DataStructures•Arrays•ArraysasParametersandReturnValues•Announcements•Practice:SwappingElements•Practice:WeatherStation
Nexttime:2DArrays
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
ExtraSlides
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.
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
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
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