Presentation is loading. Please wait.

Presentation is loading. Please wait.

U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 

Similar presentations


Presentation on theme: "U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms "— Presentation transcript:

1 U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 

2 U n i v e r s i t y o f H a i l 2 Outline 1.Arrays Extending Java Arrays Constructors Assign Method Accessor Methods Array Indexing Methods – get and put Resizing an Array – setBase and setLength 1.Multi-Dimensional Arrays Array Subscript Calculations An Implementation Constructor Array Indexing Methods – get and put Matrices Dense Matrices Canonical Matrix Multiplication 1.Singly-Linked Lists An Implementation LinkedList Constructor purage Method Accessor Methods getFirst and getLAst Methods prepend Method append Method assign Method extract Method insertAfter and insertBefore Methods

3 U n i v e r s i t y o f H a i l Lec 1

4 U n i v e r s i t y o f H a i l 4 Abstract Data Types (ADTs) include stacks, queues, ordered lists, sorted lists, hash and scatter tables, trees, priority queues, sets, and graphs. This chapter introduces the concept of Arrays and Linked list They are called Foundational Data Structure (they are the base on which almost all of the ADTs are built)

5 U n i v e r s i t y o f H a i l 5 1. Arrays An array is an object that contains a collection of objects, all of the same type. int [ ] a = new int [5] Allocates an array of five integers and assigns it to the variable a The elements of an array are accessed using integer indxes. The first element of an array has always index zero All array objects in Java have an int field called length. Array-name.length returns the number of elements of an array

6 U n i v e r s i t y o f H a i l 6 1. Arrays Java checks at run time that the index used in every array access is valid (valid indices are between 0 and length - 1). If an invalid index expression is used, an IndexOutOfBoundsException exception is shown. Once allocated, the size of a java array object is fixed. The elements of an array occupy consecutive memory locations. The total storage required to represent an array can be estimated Let S(n) be the total storage (memory) needed to represent an array of n ints: S(n)  sizeof(int[ n ])  (n+1) sizeof(int)

7 U n i v e r s i t y o f H a i l 7 1. Arrays int [6] 6 int length 3 int 1 4 1 5 9 Memory representation of java arrays

8 U n i v e r s i t y o f H a i l 8 1. Arrays: Extending Java arrays  Some shortcomings of java arrays Indexes range from zero to n-1 (n is the array length) The size is fixed once it is allocated. 1 public class Array 2 { 3 protected Object [ ] data ; // array of Java objects 4 protected int base ; // the lower bound for array index 5 6 // … 7 }  Solution 4.1

9 U n i v e r s i t y o f H a i l 9 1. Arrays: Constructors 4.2 public class Array { protected Object [ ] data ; // array of Java objects protected int base ; // the lower bound for array index public Array (int n, int m) { data = new Object [n]; // allocation of an array of n Objects base = m; } public Array ( ) { this (0, 0); // n = 0 and m = 0 } public Array ( ) { this (n, 0); // m = 0 }

10 U n i v e r s i t y o f H a i l 10 1. Arrays: assign Method 4.3 public class Array { protected Object [ ] data ; // array of Java objects protected int base ; // the lower bound for array index public void assign (Array array) { if (array != this) { if (data.length != array.data.length) data = new Object [array.data.length] ; for (int i =0; i < data.length; ++i) data [i] = array.data[i] ; base = array.base; }

11 U n i v e r s i t y o f H a i l 11 1. Arrays: assign Method  The assign method provides a way to assign the elements of one array to another  It is intended to be used like this: Array a = new Array (5); Array b = new Array (5); // … b.assign (a) ; // assign the elements of a to b

12 U n i v e r s i t y o f H a i l 12 1. Arrays: Accessor Methods 4.4 public class Array { protected Object [ ] data ; // array of Java objects protected int base ; // the lower bound for array index public Object [ ] getData ( ) { return data; } public int getBase ( ) { return base; } public int getLength ( ) { return data.length; } // these three methods are used to inspect the contents of the array }

13 U n i v e r s i t y o f H a i l 13 1. Arrays: Array Indexing Methods: get and put  The elements of a Java array are accessed by enclosing the index expression between brackets [ ]. a[2] = b[3];  When using the Array class, we can access its elements like this: a.getData( )[2] = b.getData( )[3];  Unfortunately, the syntax in this case is ugly. We can however, define methods for indexing an array like this: a.Put (2, b.get (3));

14 U n i v e r s i t y o f H a i l 14 1. Arrays: Array Indexing Methods: get and put 4.5 public class Array { protected Object [ ] data ; // array of Java objects protected int base ; // the lower bound for array index public Object get (int position) { return data [position - base]; // takes an index position, and returns the element found in the // array at that given position } public void put (int position, Object object) { data [position - base] = object ; // takes an index and an Object and stores the object in the array // at the given position }

15 U n i v e r s i t y o f H a i l 15 1. Arrays: Resizing an Array: setBase and setLength 4.6 public class Array { protected Object [ ] data ; // array of Java objects protected int base ; // the lower bound for array indices public void setBase (int base) { this.base = base; // modifies the base field } public void setLength (int newLength) { if (data.length != newLength) { Object [ ] newData = new Object [newLength] ;// create array newdata of type object with newlength int min = data.length < newLength ? ; // ternary operator to assign data.length : newLength; // minimum(data.length,newLength) to min for (int i = 0; i < min; ++i) newData [i] = data[i]; // copies the old array elements to the new array data = newData; }

16 U n i v e r s i t y o f H a i l Lec 2

17 U n i v e r s i t y o f H a i l 17 2. Multi-Dimensional Arrays  The Java does not really support multi-dimensional arrays.  In Java, a two-dimensional array x is really an array of one-dimensional arrays int [ ][ ] x = new int [3][5]; x[i] selects the ith one-dimensional array x[i][j] selects the jth element from that array  The multi-dimensional arrays have the same things of simple one- dimensional arrays ( Indices range from zero to length-1 for each dimension, no array assignment operator, the number of dimensions and the size of each dimension are fixed once the array has been allocated).

18 U n i v e r s i t y o f H a i l 18 2. Multi-Dimensional Arrays: Array Subscript Calculations  The memory of a computer is essentially a one-dimensional array  A natural way to implement a multi-dimensional array is to store its elements in a one-dimensional array.  We need a mapping function to switch from multi-dimensional array indices into one-dimensional array index. int [ ] [ ] a = new int [2][3]; int [ ] b = new int [6]; Given an element a[i][j] which element b[k] it corresponds? We need a mapping function f such that k = f(i, j)

19 U n i v e r s i t y o f H a i l 19 2. Multi-Dimensional Arrays: Array Subscript Calculations  The mapping function determines the way in which the elements of a multi-dimensional array are sorted in memory.  The most common way to represent an array is in row-major order. a[1][2]b[5] a[1][1]b[4] a[1][0]b[3] a[0][2]b[2] a[0][1]b[1] a[0][0]b[0] ValuePosition row 0 row 1 int [ ] [ ] a = new int [2][3];

20 U n i v e r s i t y o f H a i l 20 2. Multi-Dimensional Arrays: Array Subscript Calculations  Suppose we have an nD array a with dimensions:  Then the position of the element is given by Where

21 U n i v e r s i t y o f H a i l 21 2. Multi-Dimensional Arrays: An implementation  In this section we illustrate the implementation of a multi-dimensional array using a one-dimensional array. public class MultiDimensionalArray { int [ ] dimensions ; // n dimensions int factors ; // n elements the j th element = f j Object [ ] data ; // used to hold the elements of the multi-dimensional // array in row-major order. // … }

22 U n i v e r s i t y o f H a i l 22 2. Multi-Dimensional Arrays: Constructor public class MultiDimensionalArray { int [ ] dimensions ; // n dimensions int factors ; // n elements the jth element = fj Object [ ] data ; // used to hold the elements of the multi-dimensional array public MultiDimensionalArray (int [ ] arg) { dimensions = new int [arg.length]; factors = new int [arg.length]; int product =1; for (int i = arg.length-1; i>=0; --i) { dimensions [i] = arg[i]; factors[i] = product; product * = dimensions[i]; } data = new Object [product]; }

23 U n i v e r s i t y o f H a i l 23 2. Multi-Dimensional Arrays: An implementation  To create a 3  5  7 three-dimensional array, we invoke the constructor like this. MultiDimensionalArray a = new MultiDimensionalArray (new int [ ]{3, 5, 7});  The constructor copies the dimensions of the array into the dimensions array, and then it computes the factors array.  The constructor then allocates a one-dimensional array of length m given by:

24 U n i v e r s i t y o f H a i l 24 2. Multi-Dimensional Arrays: Array Indexing Methods – get and put  The elements of a multi-dimensional array are indexed using the get and put methods. We can access the (i, j, k)th element of a three-dimensional array a: a.get (new int [ ] {i, j, k});  We can modify the (i, j, k)th element like a.put (new int [ ] {i, j, k}, value);

25 U n i v e r s i t y o f H a i l 25 2. Multi-Dimensional Arrays: Array Indexing Methods – get and put public class MultiDimensionalArray { int [ ] dimensions ; // n dimensions int factors ; // n elements the jth element = fj Object [ ] data ; // used to hold the elements of the multi-dimensional array protected int getOffset (int [ ] indices) { if (indices.length != dimensions.length) throw new IllegalArgumentException(“wrong number of indices”); int offset =0; for (int i = 0; i < dimension.length; ++i) { if (indices [i] = dimensions [i]); throw new IndexOutOfBoundsException( ); offset += factors [i] * indices [i]; } return offset; } // Continue the program in the next slide

26 U n i v e r s i t y o f H a i l 26 2. Multi-Dimensional Arrays: Array Indexing Methods – get and put public Object get (int [ ] indices) { return data [getOffset (indices)] ; } public void put (int [ ] indices, Object object) { data [getOffset (indices)] = object; }

27 U n i v e r s i t y o f H a i l 27 2. Multi-Dimensional Arrays: Matrices  In this section we consider two dimensional matrices of doubles. Matrix interface { double get (int i, int j); // get an element void put (int i, int j, double d) // insert an element Matrix transpose (); Matrix times (Matrix matrix); Matrix plus (Matrix matrix); }

28 U n i v e r s i t y o f H a i l 28 2. Multi-Dimensional Arrays: Dense Matrices  The simplest way to implement a matrix is to use an array of arrays public class DenseMatrix implements Matrix { protected int numberOfRows; protected int numberOfColumns; protected double [ ][ ] array; public DenseMatrix (int numberOfRows, int numberOfColumns) { this.numberOfRows = numberOfRows ; this.numberOfColumns = numberOfColumns ; array = new double [numberOfRows][numberOfColumns]; }

29 U n i v e r s i t y o f H a i l 29 2. Multi-Dimensional Arrays: Canonical Matrix Multiplication  Given an m  n matrix A and an n  p matrix B, the product C = AB is an m  p matrix.  The elements of the result matrix are given by:  To compute the product matrix C, we need to compute mp summations each of which is the sum of n product terms.

30 U n i v e r s i t y o f H a i l 30 2. Multi-Dimensional Arrays: Canonical Matrix Multiplication public class DenseMatrix implements Matrix { protected int numberOfRows; protected int numberOfColumns; protected double [ ][ ] array; public Matrix times (Matrix mat) { DenseMatrix arg = (DenseMatrix) mat; if (numberOfColumns != arg.numberOfRows) throw new IllegalArgumentException (“incompatible matrices”); DenseMatrix result = new DenseMatrix (numberOfRows, arg.numberOfColumns); for (int i = 0; i < arg.numberOfRows; ++i) { for (int j = 0; j < arg.numberOfColumns; ++j) { double sum = 0; for (int k = 0; k < numberOfColumns; ++k) sum+ = array [i][k] + arg.array [k][j]; result.array [i][j] = sum; } } return result; } }

31 U n i v e r s i t y o f H a i l Lec 3

32 U n i v e r s i t y o f H a i l 32 3. Singly-Linked Lists  The singly-linked list is the most basic of all the linked data structures.  A singly-linked list is simply a sequence of dynamically allocated objects, each of which refers to its successor in the list. head (a) tail head (b) head Sentinel (c) tail (d)

33 U n i v e r s i t y o f H a i l 33 3. Singly-Linked Lists  This type is the basic singly-linked list.  Each element of the list refers to its successor.  The last element contains the null reference  One variable, labeled head is used to keep track of the list.  This type of singly-linked list is inefficient if we want to add elements to the end of the list (we need to locate the last element). head (a)

34 U n i v e r s i t y o f H a i l 34 3. Singly-Linked Lists  A second variable tail is used to add elements to the tail easily. tail head (b)

35 U n i v e r s i t y o f H a i l 35 3. Singly-Linked Lists  The sentinel element is never used to hold data  It is used to simplify the programming of certain operations (for example, the head variable is never modified by adding new elements)  This list is circular: the last element refers to the sentinel.  In that case insertion in the head, in the tail or in any position is the same operation. head Sentinel (c)

36 U n i v e r s i t y o f H a i l 36 3. Singly-Linked Lists  The variable tail refers to the last element of the list.  The last element refers to the first element  It is easy in this case to insert both at the head and at the tail of this list. tail (d)

37 U n i v e r s i t y o f H a i l 37 3. Singly-Linked Lists  The empty singly-linked list for the four types described before are as following head (a) tail head (b) head Sentinel (c) tail (d)

38 U n i v e r s i t y o f H a i l 38 3. Singly-Linked Lists: An Implementation  We will implement the second type of singly-linked list. LinkedList head tail Element datum next 3 Integer Element datum next 1 Integer Element datum next 4 Integer

39 U n i v e r s i t y o f H a i l 39 3. Singly-Linked Lists: An Implementation public class LinkedList { protected Element head; protected Element tail; public final class Element // used to represent the elements of a linked list { Object datum; Element next; Element (Object datum, Element next) { this.datum = datum; this.next = next; ) public Object getDatum ( ) { return datum; } public Object getNext ( ) { return next; }

40 U n i v e r s i t y o f H a i l 40 3. Singly-Linked Lists: LinkedList Constructor public class LinkedList { protected Element head; protected Element tail; public LinkedList ( ) { } // … } The code for the no-arg LinkedList constructor is: Since the fields head and tail are initially null, the list is empty by default.

41 U n i v e r s i t y o f H a i l 41 3. Singly-Linked Lists : purge(clean) Method public class LinkedList { protected Element head; protected Element tail; public void purge ( ) { head = null; tail = null; } // … } The purge method is used to discard the current list contents and to make the list empty again.

42 U n i v e r s i t y o f H a i l 42 3. Singly-Linked Lists: Accessor Methods public class LinkedList { protected Element head; protected Element tail; public Element getHead ( ) { return head ; } public Element getTail ( ) { return tail ; } public boolean isEmpty ( ) { return head == null ; // indicates whether the list is empty } // … }

43 U n i v e r s i t y o f H a i l 43 3. Singly-Linked Lists: getFirst and getLast Methods public class LinkedList { protected Element head; protected Element tail; public Object getFirst ( ) { if (head == null) throw new ContainerEmptyException (); return head.datum ; // returns the first element of the list } public Object getLast ( ) { if (tail == null) throw new ContainerEmptyException (); return tail.datum ; ; // returns the last element of the list }

44 U n i v e r s i t y o f H a i l 44 3. Singly-Linked Lists: prepend Method public class LinkedList { protected Element head; protected Element tail; public void prepend (Object item) // insert an element in front of the first element of the list { Element tmp = new Element (item, head) ; if (head == null) tail = tmp; head = tmp ; // update the head to refer the new first element } // … }

45 U n i v e r s i t y o f H a i l 45 3. Singly-Linked Lists: append Method public class LinkedList { protected Element head; protected Element tail; public void append (Object item) // insert an element at the tail of the list { // the new element becomes the new tail of the list Element tmp = new Element (item, null) ; // allocates a new element // the datum field is initialized with item and the next field is set to null if (head == null) // the list is empty head = tmp; else tail.next = tmp ; tail = tmp; // update the tail to refer the new last element } // … }

46 U n i v e r s i t y o f H a i l 46 3. Singly-Linked Lists: assign Method public class LinkedList { protected Element head; protected Element tail; public void assign (LinkedList list) // assign the elements of a linked list { // to another list if (list != this) { purge(); // the new list must be empty for (Element ptr =list.head; ptr !=null; ptr = ptr.next) append (ptr.datum); // add an element at the tail of the new list } // … }

47 U n i v e r s i t y o f H a i l 47 3. Singly-Linked Lists: extract Method public class LinkedList { protected Element head; protected Element tail; public void extract (Object item) // to delete an element from the list { Element ptr = head; Element prevPtr = null; while (ptr != null && ptr.datum != item) // searches for the element to be deleted { prevPtr = ptr; ptr = ptr.next ; } if (ptr == null) // the element is not found throw new IllegalArgumentException (“item not found”); if (ptr == head) head = ptr.next; else prevPtr.next = ptr.next; if (ptr == tail) tail = prevPtr; }

48 U n i v e r s i t y o f H a i l 48 3. Singly-Linked Lists: insertAfter and insertBefore Methods public class LinkedList { protected Element head; protected Element tail; public final class Element { Object datum ; Element next ; public void insertAfter (Object item) { next = new Element (item, next) ; if (tail == this) tail = next ; } public void insertBefore (Object item) { Element tmp = new Element (item, this) ; if (this == head) head = tmp ; else { Element prevPtr = head; while (prevPtr != null && prevPtr.next != this) prevPtr = prevPtr.next; prevPtr.next = tmp; } } } }

49 U n i v e r s i t y o f H a i l END


Download ppt "U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms "

Similar presentations


Ads by Google