lecture4: arrays bohyung han cse, postech [email protected] csed233: data structures (2014f)

22
Lecture4: Arrays Bohyung Han CSE, POSTECH [email protected] CSED233: Data Structures (2014F)

Upload: eustacia-mason

Post on 05-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

Lecture4: Arrays

Bohyung HanCSE, POSTECH

[email protected]

CSED233: Data Structures (2014F)

Page 2: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

2 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Arrays

• A data structure holding a group of variables under a single identifiers

byte[] anArrayOfBytes; int[] anArrayOfLongs; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles;boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings;

int[] a;a = new int[2];int[] b = {1, 2, 3, 4};int bLength = b.length;

// array declaration without assignment// specify the length of the array// array declaration with assignment// get the length of an array

Page 3: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

3 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Array

• Two dimensional arrays‐ Array of arrays

Size of two dimensional array‐• Number of rows: Y.length• Number of elements in each row: Y[i].length• Note: Number of elements in each row may be different.

• Java: Array class http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

int[][] Y = new int[8][10];

Page 4: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

4 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Abstract Data Type (ADT)

• Definition A mathematical model of the data objects that make up a data type

as well as the functions that operate on these objects Defined indirectly, by the operations that may be performed on it and

by mathematical constraints on the effects of those operations

• ADT is composed of A data structure A set of operations (called the methods or operations) A precise description of the types of the methods (called a signature) A precise set of rules about how it behaves (called the abstract

specification or the axiomatic description) An implementation hidden from the programmer

Page 5: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

5 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Array List ADT

• Array list is not array, but an extension of array. An array list stores a sequence of arbitrary objects. An element can be accessed, inserted or removed by specifying its

index (number of elements preceding it). An exception is thrown if an incorrect index is given, e.g., negative one. Java: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

• Java: Exception An event, which occurs during the execution of a program, that disrupts

the normal flow of the program's instructions The Java platform provides numerous exception classes.

• All the classes are descendants of the Throwable class.• All allow programs to differentiate among the various types of exceptions.

Example: if (size == 0) { throw new EmptyStackExcep-tion(); }

Page 6: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

6 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Array List ADT

• Main methods get(integer i): returns the element at index i without removing

it set(integer i, object o): replaces the element at index i

with o and returns the old element add(integer i, object o): inserts a new element o to have

index i remove(integer i): removes and returns the element at index i

• Additional methods: size(): returns the number of elements in this list isEmpty(): returns true if this list contains no elements

Page 7: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

7 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Array Based Implementation‐

• Array A of size n

• Size of array list Number of elements in the array Stored in a variable

• Operations get(i):

• Returns A[i]• Runs in time

set(i,o):• Performs t = A[i] and A[i] = o, and returns t• Runs in time

A0 1 2 ni

Page 8: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

8 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Element Insertion

• Operation add(o) Adds an object at the end of the array list, A[n] Increases the size of the array by 1

• Time complexity

A

0 1 2 n

A

0 1 2 no

Page 9: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

9 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Element Insertion

• Operation add(i,o) Makes a room for the new element by shifting forward the n i ‐

elements A[i], …, A[n‐1] Adds an object at A[i]

• Worst case time complexity when i = 0

A0 1 2 ni

A0 1 2 ni

A0 1 2 n

oi

Page 10: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

10 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Element Removal

• Operation remove(i) Removes an element, A[i] Fills the hole left by the removed element by shifting backward the n‐i‐1 elements A[i+1], …, A[n‐1]

• Worst case time complexity when i = 0

A0 1 2 ni

A0 1 2 n

oi

A0 1 2 ni

Page 11: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

11 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Performance

• Space complexity The space used by the data structure:

• Time complexity of methods

Method Time complexity

size()

insert()

get(i)

set(i,o)

add(o)

add(i,,o) time in the worst case

remove(i) time in the worst case

Page 12: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

12 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Growable Array based Array List‐

• When the array is full in an add operation Throwing an exception Replacing the array with a larger one

• How large should the new array be? Incremental strategy: increase the size by a constant Doubling strategy: double the size

Page 13: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

13 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Growable Array based Array List‐

Algorithm add(o) Input array A of n integers Output array A of n+1 integers

if n = A.length thenS new array

of size …

for i 0 to n-1 do

S[i] A[i]

A S

n n + 1A[n-1] o

Create a new array S (larger than A)

Copy the elements in A to S

Replace A with S

Increase array size by 1 and add oas the last element

Page 14: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

14 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Comparison of the Strategies

• Incremental strategy vs. doubling strategy Comparison by analyzing the total time needed to perform a

series of add(o) operations We assume that we start with an empty array. We call amortized time of an add operation the average time taken by

an add over the series of operations, i.e.,

Page 15: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

15 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Incremental Strategy

• How many times is array replaced? times (: increment constant)

• The total time of a series of add operations is proportional to

• Time complexity

The amortized time of an add operation is .

𝑛+ (𝑐+2𝑐+3𝑐+4𝑐+…+𝑘𝑐 )=𝑛+𝑐𝑘 (𝑘+1 )

2

Number of iterations Constructions of new array with larger sizes

Page 16: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

16 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Doubling Strategy

• How many times is array replaced? times

• The total time of a series of add operations is proportional to

• Time complexity

The amortized time of an add operation is .

Geometric series

1

2

14

8

𝑛+ (1+2+4+8+⋯+2𝑘 )=3𝑛−1

Number of iterations

Constructions of new array with larger sizes

Page 17: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

17 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Example with Array Listpublic class ArrayListTest{ public static void main(String args[]) { ArrayList<Integer> IntegerList = new ArrayList<Integer>();

System.out.println("Empty array? " + Inte-gerList.isEmpty());

for(int i=0; i<20; i++) IntegerList.add(i); System.out.println("Num. of elements: " + IntegerList.-size(); for(int i=1; i<IntegerList.size(); i*=2) IntegerList.remove(i); System.out.println("Num. of elements: " + IntegerList.-size(); System.out.println("\nElements in array"); for(int i=0; i<IntegerList.size(); i++) System.out.println("\t" + i + ":" + IntegerList.get(i)); }}

Page 18: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

18 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Simple Implementation of ArrayList

import java.io.*;

public class SimpleArrayList<T>{ protected int count; // number of elements in Ar-rayList protected T[] contents; // array of stored values protected static int DEFAULT_CAPACITY = 10;

// constructors public SimpleArrayList() { contents = (T[]) new Object[DEFAULT_CAPACITY]; }

public SimpleArrayList(int initCapacity) { contents = (T[]) new Object[initCapacity]; }

Page 19: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

19 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Simple Implementation of ArrayListpublic void add (T newElem){ if (count == contents.length) { T temp[] = contents; contents = (T[]) new Object[2*count];

for ( int i = 0; i < count; i++ ) contents[i] = temp[i]; } contents[count++] = newElem ;}

public T get(int index){ if (index < 0 || index >= count ) throw new IndexOutOfBoundsException("ArrayList:" + index) ; return contents[index] ;}

Page 20: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

20 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Simple Implementation of ArrayList

public int size() { return count; }

public T remove (int index) { if (index < 0 || index >= count ) throw new IndexOutOfBoundsException("ArrayList:" + index);

T temp = contents[index]; for (int j = index; j < count‐1; j++) contents[j] = contents[j+1]; count‐‐;

return temp; }}

Page 21: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

21 CSED233: Data Structuresby Prof. Bohyung Han, Fall 2014

Summary

• An ADT consists of A data structure:

• A collection of data, and• its organization, structure, properties;

The operations that can be performed:• What can be done to change, manipulate, or look at the data

• Information hiding The “user” of an ADT must know enough to:

• Create one of them, and• Perform the operations,

but not• What fundamental construct is used to store the data, and• How the operations are done.

Some members, constructors and methodsof ArrayList should be known.

Detailed implementation of ArrayListclass does not need to be known.

Page 22: Lecture4: Arrays Bohyung Han CSE, POSTECH bhhan@postech.ac.kr CSED233: Data Structures (2014F)

22