Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 216 times |
Download: | 2 times |
ArraysArrays
CSC 171 FALL 2001
LECTURE 10
History: Alan Turing History: Alan Turing Founder of Computer ScienceFounder of Computer Science
1937 - Alan Turing developed the idea of a "Universal Machine" capable of executing any describable algorithm, and forming the basis for the concept of "computability".
Turing's ideas differed from those of others who were solving arithmetic problems by introducing the concept of "symbol processing".
The Turing MachineThe Turing MachineTape memory (movable)
a c ab cbbaa
Read head
h
q3 q2
q1
q0
State machine
The Turing MachineThe Turing Machine
A Turing machine is a quintuple (K,,,s,H)– K is a finite set of states is an alphabet of symbols– s is the initial state– H is the halting state is the transition function
From (K-H) x To K x ( U {move_tape_left, move_tape_right})
The Turing TestThe Turing Test Turing put forward the idea of an 'imitation game',
in which a human being and a computer would be interrogated under conditions where the interrogator would not know which was which, the communication being entirely by textual messages.
Turing argued that if the interrogator could not distinguish them by questioning, then it would be unreasonable not to call the computer intelligent.
Turing's 'imitation game' is now usually called 'the Turing test' for intelligence.
ArraysArrays
Suppose we want to write a program that reads a set of test grades and prints them, marking the highest grade?65.2
81.7
31.3
95.4 < - highest grade
76.1
58.6
Individual data itemsIndividual data items
If we knew that there were always 150 students in the class, we could store the data as individual variables– score1,score2,score3, . . , score150
What would the data entry code look like?What would the printing code look like?How about finding the max?
ArraysArrays
An array is a collection of data items of the same type
Every element of the collection can be accessed separately.
Constructing ArraysConstructing Arrays
double [] data = new double[10];
Setting Array valuesSetting Array values
To get values into an array you need to specify which slot you want to use.
Specification is done with the [ ] operatorThe [ ] operator follows the name of the
arrayThe [ ] operator encloses and integer-valued
expression called the index or subscript
Setting array valuesSetting array values
data[4] = 29.95;
Using array valuesUsing array values
Similar to setting
int i = 4 ;
System.out.println(“data[“+i+”] ==“+ data[i]);
> data[4] ==29.95
Array data itemsArray data itemsSuppose we want to write a program that
reads a set of test grades and prints them, marking the highest grade?
What would the data entry code look like?What would the printing code look like?How about finding the max?
Array issuesArray issues
Does it work?
double [] data = new double[10];
data[10] = 5.4;
Array issuesArray issues
Does it work?
double [] data = new double[10];data[10] = 5.4;
When the program runs, an out-of-bounds subscript generates an exception and terminates the program – why?
Array issuesArray issues
Can we search for the top grade as follows
double maxScore = data[0];
for (int i = 1;I<=data.length;i++)
If (data[i] > maxScore)
maxScore = data[i];
Array issuesArray issues
An array of length n has index values from 0 to (n-1)
double maxScore = data[0];
for (int i = 1;I<data.length;i++)
If (data[i] > maxScore)
maxScore = data[i];
Array issuesArray issues
Does it work?
public static void main(String[] args){ double[] data;
If (data[0] > 4.0)
System.out.println(“GT 4!”);
}
Array issuesArray issues
Arrays must be allocated!
public static void main(String[] args){ double[] data = new double[10];
If (data[0] > 4.0)
System.out.println(“GT 4!”);
}
Array issuesArray issues
Arrays can be initialized!
public static void main(String[] args){ double[] data = {2,3,4,5,6};
If (data[0] > 4.0)
System.out.println(“GT 4!”);
}
// note: new int[] {2,3,4,5,6} ; is also legal
Copying ArraysCopying Arrays
Is this ok?
double [] data = new double[10];
double[] testScores;
testScores = data;
Copying ArraysCopying Arrays
Is this ok?
double [] data = new double[10];
double[] testScores;
testScores = data;
How many arrays are there?
Copying Array REFERENCESCopying Array REFERENCESdouble [] data = new double[10];double[] testScores;testScores = data;
Copying ArraysCopying Arrays
So, what if we want to make two “real” copies – what does the code look like?
Write a method so that
int[] x = {3,4,5,6,7,8,9,10};
int[] y = myCopy(x);
CopyingCopying
public static int[] myCopy(int[] x){
int[] r_arry = new int[x.length];
for (int i = 0 ; i< x.length;i++)
r_arry[i] = x[i];
return r_arry;
}
System.arrayCopySystem.arrayCopy
//System.arraycopy(from,fromstart,to,toStart,count);System.arraycopy(data,0,prices,0,data.length);
CSC 171 GRADES FALL 2001
0
5
10
15
20
25
30
35
40
I N E D- D D+ C- C C+ B- B B+ A- A
GRADE
CO
UN
T
History: Colossus History: Colossus Bletchley ParkBletchley Park
1940 A major need for supporting the war effort was to decrypt the intercepted messages of the German forces. Encrypted in the early years using the US designed ENIGMA, a team at Bletchley Park, built a series of machines culminating in 1943 with Colossus.
More ArraysMore Arrays
Suppose we want to write a program that reads a set of test product names, prices, and quality scores prints them, marking the best value? (score/prices)Digital 500X, $3499.00, score 73
ZEOS Pentium-III/500, $2545.00, score 70
Micro Express MF, $2195.00, score 72 < - best value
Polywell Poly 450IP, $2099.00, score 30
Parallel ArraysParallel Arrays
One solution, can you think of a better one?
Arrays of ObjectsArrays of ObjectsEasier to deal with - arrays hold references
Multidimensional ArraysMultidimensional Arrays
Arrays of arrays– Arrays are objects– Arrays hold references to objects– Ergo, arrays can hold arrays
Tables are 2D arraysTables are 2D arraysint size = 5;int[][] mtable = new int[size][size];for(i=0;i<size;i++)
for(int j=0;j<size;j++)mtable[i][j] = (i+1)*(j+1);
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
// how easy to modify code ????
int[][] mtable = new int[5][5];
for(i=0;i<5;i++)
for(int j=0;j<5;j++)
mtable[i][j] = (i+1)*(j+1);
Arrays of ArraysArrays of Arrays
int [][] powers = new int[10][10];
Allocating arrays of arraysAllocating arrays of arrays
int size = 10;int[][] mtable = new int[size][];for(i=0;i<mtable.length;i++) {
mtable[i]= new int[size];for(int j=0;j<mtable[i].length;j++)
mtable[i][j] = (i+1)*(j+1);
}
AlternatelyAlternately
The following is legal.What is the structure?
int[][] b = new int[5][];
for (int i=0;i<b.length;i++)
b[i] = new int[i+1];
AlternatelyAlternately
int[][] b = new int[5][];
for (int i=0;i<b.length;i++)
b[i] = new int[i+1];
This is known as a triangular array
Is b[3][1] a legal reference or b[1][3]?
Passing ArraysPassing ArraysIn JAVA
– Primitives are passed by value A copy of the variable is made & used Modifications made do not affect calling value public void myAdd(int x) { x++;}
– Objects are passed by reference Since the reference is passed it is possible to change
the value in the calling method Public void myAdd (int[] x) {x[0]++;}
Pass by valuePass by value
public class passArry {
public static void main(String args[]){
int x1 = 3;
System.out.println("x1 == "+x1);
myAdd(x1);
System.out.println("x1 == "+x1);
}
public static void myAdd(int x) {x++;}
}
Pass by referencePass by reference
public class passArry {
public static void main(String args[]){
int[] x2 = {4,5,6};
System.out.println("x2[0] == "+x2[0]);
myAdd(x2);
System.out.println("x2[0] == "+x2[0]);
}
public static void myAdd(int[] x) {x[0]++;}
}
ExerciseExercise
Write a method that takes an integer array and prints the values
ExerciseExercise
Write a method that takes an integer array and prints the values
public static int myPrint(int[] x){
for (int i = 0 ; i<x.length;i++)
System.out.println(x + “[“+i+”] == “+ x[i]);
}
ExerciseExercise
Write a method that takes an integer array, and two integer indices and swaps the value
ExerciseExerciseWrite a method that takes an integer array,
and two integer indices and swaps the value
public static void mySwap(int[] x, int i, int j){ int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
ExerciseExercise
Write a method that takes an integer array and returns the index of the maximum value
ExerciseExercise
Write a method that takes an integer array and returns the index of the maximum value
public static int myMax(int[] x){ int rvalue = 0;for (int i = 0 ; i<x.length;i++) if (x[i] > x[rvalue]) rvalue = i;return rvalue;
}
ExerciseExercise
Overload the max finder to take an array and an index – the method now returns the index of the maximum value >= the index passed in
ExerciseExercise
Overload the max finder to take an array and an index – the method now returns the index of the maximum value >= the index passed in
public static int myMax(int[] x, int j){
int rvalue = j;
for (int i = j ; i<x.length;i++)
if (x[i] > x[rvalue]) rvalue = i;
return rvalue;
}
SortingSorting
Write a method that takes an integer arrayLoop through all the positions in the array,
one after the otherAt each (current) position, find the max
from that position to the rest of the array.Swap the value with the current positionThis is termed selection sort
Selection SortSelection SortDoes it work?
public void selSort(int x){for (int i = 0 ; i<x.length;i++){
int temp = myMax(x,i);mySwap(x,i,temp);
}
Can you prove it works?What is the loop invariant?
SortingSorting
Write a method that takes an integer array Loop through all the positions in the array, one
after the other At each (current) position, compare the value to
the next in line. If the next is > the current swap the value with the
current position How many times do I have to do this? This is termed bubble sort
Bubble SortBubble SortDoes it work?
public void bubSort(int x){for (int i = 0 ; i<x.length;i++){
for (int j = 0 ; j<(x.length-1);j++){If (x[ j ] < x[ j+1 ])
mySwap(x,j,j+1); }}
}
Question to ponderQuestion to ponder
Which is “better” – bubble sort– selection sort
What do you mean by “better”?– Running time on same sized array– Number of swaps– Memory usage– Simplicity & reliability