39
Arrays

Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively: flow of control iteration/conditionals modular design

  • View
    216

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Arrays

Page 2: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Programming: The Big Picture Three fundamental ideas to understand and

use effectively: flow of control

iteration/conditionals modular design

subroutines/recursion data representation

data types/data structures

Page 3: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Data Structures

A data structure is a way of storing data in a computer so that it can be used efficiently typically data that is more complex than just a

number or a truth value The choice of data structure used to store

data can impact the performance of your program

Page 4: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Data Structures

Given a collection of data: 1, 1, 5, 3, 1, 5, 4, 1, 1

How do we want to store this? [4*1, 0*2, 1*3, 1*4, 2*5] (bag) {1,3,4,5} (set) [1,1,5,3,1,5,4,1,1] (list)

Depends on the application e.g. voting vs. scheduling

Page 5: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Data Structures

Given a collection of data: 1, 1, 5, 3, 1, 5, 4, 1, 1

Do we expect more data? more data arriving at the tail? more data arriving in the middle?

All of these factors together should be considered in choosing a data representation

Page 6: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Arrays

An array is an ordered list of values

0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91

An array of size N is indexed from zero to N-1

scores

The entire arrayhas a single name

Each value has a numeric index

This array holds 10 values that are indexed from 0 to 9

Page 7: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Arrays

A particular value in an array is referenced using the array name followed by the index in brackets

For example, the expression

scores[2]

refers to the value 94 (the 3rd value in the array)

That expression represents a place to store a single integer and can be used wherever an integer variable can be used

Page 8: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Arrays

For example, an array element can be assigned a value, printed, or used in a calculation:

scores[2] = 89;

scores[first] = scores[first] + 2;

mean = (scores[0] + scores[1])/2;

System.out.println ("Top = " + scores[5]);

Page 9: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Arrays

Limitations: Array length is fixed when the array is created Can only hold a single type

so… Can’t lengthen an array mid-program Can’t store an int and a String in the same

array

Page 10: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Arrays The values held in an array are called array

elements

An array stores multiple values of the same type – the element type

The element type can be a primitive type or an object reference

arrays of integers, arrays of Strings, arrays of BankAccounts

In Java, the array itself is an object that must be instantiated

Page 11: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Declaring Arrays

Use the new syntax To create a pointer to an array, append a [] to

the element type String[] names; int[] scores;

Like other object types, this creates a reference – not an object

Page 12: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Declaring Arrays

To allocate the memory for the array: e.g. create an array of 10 ints:

new int[10]; all at once:

int[] scores = new int[10]; Creates this:

scores

Page 13: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Declaring Arrays

Note that the type of the variable scores is int[] An array of integers

The array type does not specify its size The type is not an “array of size 10”

However, every object of type array has a specified size

Page 14: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Declaring Arrays

Some other examples of array declarations:

float[] prices = new float[500];

boolean[] flags;

flags = new boolean[20];

char[] codes = new char[1750];

Page 15: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Manipulating Array Elements

Some sample array commands:int[] myArray = new int[100];

myArray[0] = 2;

myArray[4] = myArray[0] + 1;

System.out.println(myArray[4]);

\\ prints 3

myArray[99] = 2; \\ ok

myArray[100] = 2; \\ error

Page 16: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Bound Checking

Array of size N has indices 0,…,N-1 Referencing an element with an index larger

than N-1 results in an “ArrayIndexOutOfBoundsException”

This is called automatic bounds checking

Page 17: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Bounds Checking

It’s common to produce one-off errors:int[] codes = new int[100];

for (int index=0; index <= 100; index++)

codes[index] = index*50 + epsilon;

Solution: use the public length constant and the strictly less than relation

Page 18: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

The length Constant

Each array object has a public constant called length that holds the number of elements note: not the highest index

It is referenced with the array name:e.g. codes.length

So this is a safer loop: for (int index=0; index < codes.length; index++)

codes[index] = index*50 + epsilon;

Page 19: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

The Iterator for Loop

Can also use the “iterator version” of the for loop:

for (int score : scores)

System.out.println (score);

This is only appropriate when processing all array elements from top (lowest index) to bottom (highest index)

Page 20: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Alternate Array Syntax

The brackets of the array type can be associated with the element type or with the name of the array

Therefore the following two declarations are equivalent:

float[] prices;

float prices[];

The first format generally is more readable and should be used

Page 21: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Initializer Lists

An initializer list can be used to instantiate and fill an array in one step

The values are delimited by braces and separated by commas:

int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};

char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

Page 22: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Initializer Lists

Note that when an initializer list is used:

the new operator is not used

no size value is specified

The size of the array is determined by the number of items in the initializer list

An initializer list can be used only in the array declaration

Page 23: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Arrays as Parameters

An entire array can be passed as a parameter

Example: the main method takes an argument of type String[]

This array is obtained from command-line arguments

Page 24: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Command Line Arguments

public class CommandLineTest

{

public static void main (String[] args)

{

System.out.println(“First parameter: “ + args[0]);

System.out.println(“Second parameter: + args[1]);

}

}

Page 25: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

A two-dimensional array can be thought of as a table of elements, with rows and columns

onedimension

twodimensions

Two Dimensional Arrays

Page 26: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Two Dimensional Arrays

Declared as follows:int[][] scores = int[12][10];

Elements referenced by pairs:value = scores[4][8]; \\two bounds to check

To be accurate… this is just an array of arrays… not a new type

An entire row can be referenced with a single indexarrayvariable = scores[4];

Page 27: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

The ArrayList Class

Included in the java.util package Essentially, it is an array that can grow and

shrink add elements and remove elements

Another advantage: can store multiple types

Page 28: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

The ArrayList Class

Example:ArrayList lunch = new ArrayList();

lunch.add(“apple”);

lunch.add(“peanut butter sandwich”);

System.out.println(lunch);

Creates a new array list Adds two string elements Prints both out (using hidden toString() )

Page 29: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

The ArrayList Class

Elements can be inserted or removed with a single method invocation

When an element is inserted, the other elements "move aside" to make room

Likewise, when an element is removed, the list "collapses" to close the gap

The indexes of the elements adjust accordingly

Page 30: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

ArrayList Efficiency

The ArrayList class is implemented using an underlying array

The array is manipulated so that indexes remain continuous as elements are added or removed

If elements are added to and removed from the end of the list, this processing is fairly efficient

But as elements are inserted and removed from the front or middle of the list, the remaining elements are shifted

Page 31: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Searching

Page 32: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Searching

A common problem: find an item in an array find exact match find item that contains… return position return element

Page 33: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Linear Search

In general, we need to go through every element in the array

Pseudocode:for i from 0 to length – 1

if array[i]=target :

return i

return -1 \\ indicates target not in array Java implementation in text

Page 34: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Properties

Will work on any array searches every element will find target if it’s there

Problem: it is slow searches every element might not be necessary in some arrays

Page 35: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Binary Search

Suppose we have a sorted array then we can avoid looking at every element

We are looking for 17 in this array Half the array can quickly be eliminated

Look in the middle: 29 Can ignore second half of the array

-2 -1 8 14 17 23 29 37 74 75 81 87 95

Page 36: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Details

Keep track of the “candidate” part of the array Look at the middle of the candidate part Found it? DONE! Not found? Throw away one half

-2 -1 8 14 17 23 29 37 74 75 81 87 95

-2 -1 8 14 17 23 29 37 74 75 81 87 95

-2 -1 8 14 17 23 29 37 74 75 81 87 95

Page 37: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Pseudocode

first = 0 \\ start of candidate array

last = length -1 \\ end of candidate array

while first <= last

mid = (first+last)/2

if (array[mid]=target): return mid

else if (array[mid] < target): first = mid+1

else if (array[mid] > target): last = mid-1

return -1 \\ not in array

Page 38: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Example, again

-2 -1 8 14 17 23 29 37 74 75 81 87 95

first = 0, last =12, mid = 6

-2 -1 8 14 17 23 29 37 74 75 81 87 95

first = 0, last =5, mid = 2

-2 -1 8 14 17 23 29 37 74 75 81 87 95

first = 3, last =5, mid = 4

return 4

Page 39: Arrays. Programming: The Big Picture Three fundamental ideas to understand and use effectively:  flow of control iteration/conditionals  modular design

Speed

binary search example took 3 steps worst case: 4 ( approx. log2(n) )

linear search worst case: 13 (=n)

binary search is much faster for large arrays but we need the array to be sorted… how much work does that require…