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 

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Singly Linked Lists What is a singly-linked list? Why linked lists?
Chapter 24 Lists, Stacks, and Queues
Ics202 Data Structures. hh tail head (b) LinkedList head tail Element datum next 3 Integer Element datum next 1 Integer Element datum next 4 Integer.
M180: Data Structures & Algorithms in Java
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
CS Data Structures II Review COSC 2006 April 14, 2017
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are crated using the class definition. Programming techniques.
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 
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Doubly Linked Lists Doubly Linked Lists: Introduction. Doubly Linked Lists: Implementation Doubly Linked Lists: Analysis Doubly Linked Lists: Creation.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L11 (Chapter 20) Lists, Stacks,
Singly Linked Lists Singly Linked Lists: Introduction. Singly Linked Lists: Implementation. Singly Linked Lists: Analysis. Singly Linked Lists: Creation.
Multidimensional Arrays in Java Vidhu S. Kapadia.
Chapter 4 Linked Lists Anshuman Razdan Div of Computing Studies
Introduction of Arrays. Arrays Array form an important part of almost all programming language. It provides a powerful feature and can be used as such.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
Stacks, Queues, and Deques
Stacks, Queues, and Deques. A stack is a last in, first out (LIFO) data structure –Items are removed from a stack in the reverse order from the way they.
Stacks, Queues, and Deques
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
CS 1031 Queues Definition of a Queue Examples of Queues Design of a Queue Class Different Implementations of the Queue Class.
Data Strcutures.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Ics202 Data Structures. class Array { protected Object[] data; protected int base; public Array (int n, int m) { data = new Object[n]; base = m; } public.
Pointers OVERVIEW.
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
A first look an ADTs Solving a problem involves processing data, and an important part of the solution is the careful organization of the data In order.
Self-Referential Classes A Self-referential class is a class that contains a reference to an object that has the same class type. –A self-referential class.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
List Interface and Linked List Mrs. Furman March 25, 2010.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Chapter Lists Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2010.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Arrays of Arrays Quick review … arrays Arrays of arrays ≡ multidimensional array Example: times table Representation in memory Ragged arrays Example:
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Data Structure and Algorithm: CIT231 Lecture 3: Arrays and ADT DeSiaMore DeSiaMorewww.desiamore.com/ifm1.
1 Data Structures and Algorithms Outline This topic will describe: –The concrete data structures that can be used to store information –The basic forms.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
LINKED LISTS.
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 
Data Structure and Algorithms
Stacks.
Stacks and Queues.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Foundational Data Structures
Linked Lists.
Collections Framework
Copyright © Aiman Hanna All rights reserved
Queues Definition of a Queue Examples of Queues
Matrix and Linked List ADTs
Presentation transcript:

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 

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

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

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)

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

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)

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 Memory representation of java arrays

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

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 }

U n i v e r s i t y o f H a i l 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; }

U n i v e r s i t y o f H a i l 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

U n i v e r s i t y o f H a i l 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 }

U n i v e r s i t y o f H a i l 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));

U n i v e r s i t y o f H a i l 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 }

U n i v e r s i t y o f H a i l 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; }

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

U n i v e r s i t y o f H a i l 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).

U n i v e r s i t y o f H a i l 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)

U n i v e r s i t y o f H a i l 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];

U n i v e r s i t y o f H a i l 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

U n i v e r s i t y o f H a i l 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. // … }

U n i v e r s i t y o f H a i l 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]; }

U n i v e r s i t y o f H a i l 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:

U n i v e r s i t y o f H a i l 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);

U n i v e r s i t y o f H a i l 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

U n i v e r s i t y o f H a i l 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; }

U n i v e r s i t y o f H a i l 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); }

U n i v e r s i t y o f H a i l 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]; }

U n i v e r s i t y o f H a i l 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.

U n i v e r s i t y o f H a i l 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; } }

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

U n i v e r s i t y o f H a i l 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)

U n i v e r s i t y o f H a i l 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)

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

U n i v e r s i t y o f H a i l 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)

U n i v e r s i t y o f H a i l 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)

U n i v e r s i t y o f H a i l 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)

U n i v e r s i t y o f H a i l 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

U n i v e r s i t y o f H a i l 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; }

U n i v e r s i t y o f H a i l 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.

U n i v e r s i t y o f H a i l 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.

U n i v e r s i t y o f H a i l 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 } // … }

U n i v e r s i t y o f H a i l 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 }

U n i v e r s i t y o f H a i l 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 } // … }

U n i v e r s i t y o f H a i l 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 } // … }

U n i v e r s i t y o f H a i l 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 } // … }

U n i v e r s i t y o f H a i l 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; }

U n i v e r s i t y o f H a i l 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; } } } }

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