Arrays
Download
1 / 91

Arrays - PowerPoint PPT Presentation


  • 147 Views
  • Updated On :

Arrays. CSC 171 FALL 2002 LECTURE 20. Arrays. 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 items.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Arrays' - allie


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Arrays l.jpg

Arrays

CSC 171 FALL 2002

LECTURE 20


Arrays2 l.jpg
Arrays

  • 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 items l.jpg
Individual 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?


Arrays4 l.jpg
Arrays

  • An array is a collection of data items of the same type

  • Every element of the collection can be accessed separately.



Slide6 l.jpg

_ the same type.An array__________ is a fixed length sequence of values of the same type.


Constructing arrays l.jpg
Constructing Arrays the same type.

double [] data = new double[10];


Slide8 l.jpg

double [] data = new double[10]; the same type.

int x = data.length ;

//instance field on arrays, x = = 10


Setting array values l.jpg
Setting Array values the same type.

  • To get values into an array you need to specify which slot you want to use.

  • Specification is done with the [ ] operator

  • The [ ] operator follows the name of the array

  • The [ ] operator encloses and integer-valued expression called the index or subscript


Setting array values10 l.jpg
Setting array values the same type.

data[4] = 29.95;

0

1

2

3

4

5

6

7

8

9


Using array values l.jpg
Using array values the same type.

  • Similar to setting

    int i = 4 ;

    System.out.println(“data[“+i+”] ==“+ data[i]);

    > data[4] ==29.95


Slide12 l.jpg

You access array elements with and integer position number, called the _______________, using the notation _______________.


Slide13 l.jpg

You access array elements with and integer position number, called the ___index_______, using the notation ____a[index]___________.


Array data items l.jpg
Array data items called the ___

  • Suppose 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 issues l.jpg
Array issues called the ___

  • Does it work?

    double [] data = new double[10];

    data[10] = 5.4;


Array issues16 l.jpg
Array issues called the ___

  • 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 issues23 l.jpg
Array issues elements in an array.

  • 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 issues24 l.jpg
Array issues elements in an array.

  • 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 issues25 l.jpg
Array issues elements in an array.

  • Does it work?

    public static void main(String[] args){ double[] data;

    If (data[0] > 4.0)

    System.out.println(“GT 4!”);

    }


Array issues26 l.jpg
Array issues elements in an array.

  • 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 issues27 l.jpg
Array issues elements in an array.

  • 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 arrays l.jpg
Copying Arrays elements in an array.

Is this ok?

double [] data = new double[10];

double[] testScores;

testScores = data;


Copying arrays29 l.jpg
Copying Arrays elements in an array.

Is this ok?

double [] data = new double[10];

double[] testScores;

testScores = data;

How many arrays are there?


Copying array references l.jpg
Copying Array REFERENCES elements in an array.

double [] data = new double[10];

double[] testScores;

testScores = data;


Copying arrays31 l.jpg
Copying Arrays elements in an array.

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


Copying l.jpg
Copying elements in an array.

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 arraycopy l.jpg
System.arrayCopy elements in an array.

//System.arraycopy(from,fromstart,to,toStart,count);

System.arraycopy(data,0,prices,0,data.length);


Clone l.jpg
Clone elements in an array.


Slide35 l.jpg

An array variable stores a ________________________. Copying the variable yields a second ____________________ to _________________ array.


Slide36 l.jpg

An array variable stores a ______reference__________. Copying the variable yields a second ______reference______________ to ____the same_____________ array.




Slide39 l.jpg

Use the _____________________________ method to copy elements from one array to another.



Slide41 l.jpg

If you run out of space in an array you need to _______________ a larger array and copy the elements into it.


Slide42 l.jpg

If you run out of space in an array you need to __allocate_____ a larger array and copy the elements into it.


Getting a bigger array l.jpg
Getting a Bigger Array __allocate_____ a larger array and copy the elements into it.


More arrays l.jpg
More Arrays __allocate_____ a larger array and copy the elements into it.

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 arrays l.jpg
Parallel Arrays __allocate_____ a larger array and copy the elements into it.

  • One solution, can you think of a better one?


Arrays of objects l.jpg
Arrays of Objects __allocate_____ a larger array and copy the elements into it.

  • Easier to deal with - arrays hold references




Multidimensional arrays l.jpg
Multidimensional Arrays into arrays of objects.

  • Arrays of arrays

    • Arrays are objects

    • Arrays hold references to objects

    • Ergo, arrays can hold arrays


Tables are 2d arrays l.jpg
Tables are 2D arrays into arrays of objects.

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

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


Arrays of arrays l.jpg
Arrays of Arrays into arrays of objects.

int [][] powers = new int[10][10];


Arrays of arrays52 l.jpg
Arrays of Arrays into arrays of objects.

int [][] pow2 = {{1,2,3},{4,5,6},{7,8,9}};


Allocating arrays of arrays l.jpg
Allocating arrays of arrays into arrays of objects.

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

}


Alternately l.jpg
Alternately into arrays of objects.

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


Alternately55 l.jpg
Alternately into arrays of objects.

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]?


Slide56 l.jpg

Two dimensional arrays form a ___________________________ arrangement. You access elements with an index pair using the notation ______________.


Slide57 l.jpg

Two dimensional arrays form a _ arrangement. You access elements with an index pair using the notation ______________.tabular, two dimensional_______ arrangement. You access elements with an index pair using the notation _____a[i][j]_________.


Passing arrays l.jpg
Passing Arrays arrangement. You access elements with an index pair using the notation ______________.

  • In 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 value l.jpg
Pass by value arrangement. You access elements with an index pair using the notation ______________.

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 reference l.jpg
Pass by reference arrangement. You access elements with an index pair using the notation ______________.

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

}


Local reference l.jpg
Local reference arrangement. You access elements with an index pair using the notation ______________.

class Student {

int age;

// …..

public void setAge(int age){

age = age;

}

}


Local reference62 l.jpg
Local reference arrangement. You access elements with an index pair using the notation ______________.

class Student {

int age;

// …..

public void setAge(int age){

this.age = age;

}

}


Exercise l.jpg
Exercise arrangement. You access elements with an index pair using the notation ______________.

  • Write a method that takes an integer array and prints the values


Exercise64 l.jpg
Exercise arrangement. You access elements with an index pair using the notation ______________.

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

    }


Exercise65 l.jpg
Exercise arrangement. You access elements with an index pair using the notation ______________.

  • Write a method that takes an integer array, and two integer indices and swaps the value


Exercise66 l.jpg
Exercise arrangement. You access elements with an index pair using the notation ______________.

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

}


Interpretive dance l.jpg
Interpretive Dance arrangement. You access elements with an index pair using the notation ______________.

Some people are “visual” learners

Some people are “aural” learners

Some people are “symbolic” learners

Some people are “body” learners

Every kindergardener learns how to sort.


Sorting l.jpg
Sorting arrangement. You access elements with an index pair using the notation ______________.

Write a method that takes an array and sorts via the kindergarden method.


Bubblesort l.jpg
Bubblesort arrangement. You access elements with an index pair using the notation ______________.

Write a method that takes an array and sorts via the kindergarden method.

public static void bubbleSort(int[] x){

for (int j=0;j<x.length;j++)

for (int i = 0 ; i<x.length-1;i++)

if (x[i] > x[i+1]) mySwap(x,i,i+1);

}

// how many comparisions do we make?


Counting comparisons l.jpg
Counting comparisons arrangement. You access elements with an index pair using the notation ______________.

If the length of the array is “n”

The outer loop executes “n” time

Each time the outer loop executes, the inner loop executes “(n-1)” time

So, we get n(n-1) comparisions


Exercise search l.jpg
Exercise: SEARCH arrangement. You access elements with an index pair using the notation ______________.

  • Write a method that takes an integer array and returns the index of the maximum value


Exercise72 l.jpg
Exercise arrangement. You access elements with an index pair using the notation ______________.

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

    }


Exercise73 l.jpg
Exercise arrangement. You access elements with an index pair using the notation ______________.

  • 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


Exercise74 l.jpg
Exercise arrangement. You access elements with an index pair using the notation ______________.

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

    }


Sorting75 l.jpg
Sorting arrangement. You access elements with an index pair using the notation ______________.

  • Write a method that takes an integer array

  • Loop through all the positions in the array, one after the other

  • At each (current) position, find the max from that position to the rest of the array.

  • Swap the value with the current position

  • This is termed selection sort


Selection sort l.jpg
Selection Sort arrangement. You access elements with an index pair using the notation ______________.

Does 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?


Swap max with first l.jpg

{1,9,2,8,3,7,4,6,5} arrangement. You access elements with an index pair using the notation ______________.

| ^

{9,1,2,8,3,7,4,6,5}

| ^

{9,8,2,1,3,7,4,6,5}

| ^

{9,8,7,1,3,2,4,6,5}

| ^

{9,8,7,6,3,2,4,1,5}

| ^

{9,8,7,6,5,2,4,1,3}

| ^

{9,8,7,6,5,4,2,1,3}

| ^

{9,8,7,6,5,4,3,1,2}

| ^

Swap max “^” with first “|”


Run time analysis l.jpg
Run time analysis arrangement. You access elements with an index pair using the notation ______________.

  • How long does it take SectionSort to run on an array of a given length?


Count the loops l.jpg
Count the loops arrangement. You access elements with an index pair using the notation ______________.

  • n is the length of the array

  • The outer (i) loop executes from 0 to n-2

    • n-1 times

  • The on each cycle of the outer loop i has a certain (different) value

  • On each cycle of the outer loop, the inner loop executes from I + 1 to n –1

    • n – i – 1 times


So we get l.jpg
So, we get arrangement. You access elements with an index pair using the notation ______________.

N-2

S (n-i-1)

i=0


Can we prove l.jpg
Can we prove ? arrangement. You access elements with an index pair using the notation ______________.

N-2

S (n-i-1) = =

i=0

n(n-1)/2


Array lists l.jpg
Array Lists arrangement. You access elements with an index pair using the notation ______________.

  • Consider Purse class

  • Purse doesn't remember individual Coin objects, just the total

  • Don't know how many coins--can't have variables coin1...coin10

  • Use ArrayList to store variable number of objectsArrayList coins = new ArrayList();coins.add(new Coin(0.1, "dime"));. . .

  • size method yields number of elements


Slide83 l.jpg

An ______________________ is a sequence of objects. arrangement. You access elements with an index pair using the notation ______________.


Slide84 l.jpg

An _ arrangement. You access elements with an index pair using the notation ______________.array list______ is a sequence of objects.


Retrieving array list elements l.jpg
Retrieving Array List Elements arrangement. You access elements with an index pair using the notation ______________.

  • Use get method

  • Index starts at 0

  • Must cast to correct type

  • Coin c = coins.get(0); // gets first coin

  • Bounds error if index is out of range

  • Most common bounds error:int n = coins.size();c = (Coin)coins.get(n); // ERROR // legal index values are 0...n-1




Slide88 l.jpg

When retrieving an element from an array list, you need to ________________ the return value of the ________________ method to the element class.


Slide89 l.jpg

When retrieving an element from an array list, you need to __cast____ the return value of the _______get__ method to the element class.


Slide90 l.jpg

Position number of an array list range from _________ to _______________. Accessing a nonexistent position results in a _________ error.


Slide91 l.jpg

Position number of an array list range from _____0____ to ________size() - 1_______. Accessing a nonexistent position results in a ___counds______ error.


ad