Download Arrays

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Control table wikipedia , lookup

Bloom filter wikipedia , lookup

Linked list wikipedia , lookup

Comparison of programming languages (associative array) wikipedia , lookup

Array data structure wikipedia , lookup

Transcript
Arrays
Programming: The Big Picture

Three fundamental ideas to understand and
use effectively:

flow of control


modular design


iteration/conditionals
subroutines/recursion
data representation

data types/data structures
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
Data Structures

Given a collection of data:


How do we want to store this?




1, 1, 5, 3, 1, 5, 4, 1, 1
[4*1, 0*2, 1*3, 1*4, 2*5]
{1,3,4,5}
[1,1,5,3,1,5,4,1,1]
Depends on the application

e.g. voting vs. scheduling
(bag)
(set)
(list)
Data Structures

Given a collection of data:


Do we expect more data?



1, 1, 5, 3, 1, 5, 4, 1, 1
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
Arrays

An array is an ordered list of values
Each value has a numeric index
The entire array
has a single name
0
scores
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
This array holds 10 values that are indexed from 0 to 9
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
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]);
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
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
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
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
Declaring Arrays

Note that the type of the variable scores is
int[]


The array type does not specify its size


An array of integers
The type is not an “array of size 10”
However, every object of type array has a
specified size
Declaring Arrays

Some other examples of array declarations:
float[] prices = new float[500];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
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
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

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
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;
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)
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
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'};
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
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
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]);
}
}
Two Dimensional Arrays

A two-dimensional array can be thought of as
a table of elements, with rows and columns
one
dimension
two
dimensions
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
index
arrayvariable = scores[4];
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
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() )
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
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
Searching
Searching

A common problem: find an item in an array




find exact match
find item that contains…
return position
return element
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
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
Binary Search

Suppose we have a sorted array

then we can avoid looking at every element
-2


-1
8
14 17 23 29 37 74 75 81 87 95
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
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
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
Example, again
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
-2
-1
return 4
8
14 17 23 29 37 74 75 81 87 95
Speed

binary search



linear search


example took 3 steps
worst case: 4 ( approx. log2(n) )
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…