Basic Definitions

43
Text Book: Text Book: M. T. Goodrich and R. Tamassia, M. T. Goodrich and R. Tamassia, "Data Structures and Algorithms in Java," 4th "Data Structures and Algorithms in Java," 4th edition, 2006, Wiley & Sons, Inc., ISBN 978- edition, 2006, Wiley & Sons, Inc., ISBN 978- 0471738848 0471738848 . .

description

Text Book: M. T. Goodrich and R. Tamassia, "Data Structures and Algorithms in Java," 4th edition, 2006, Wiley & Sons, Inc., ISBN 978-0471738848. Basic Definitions. Data Structures : - PowerPoint PPT Presentation

Transcript of Basic Definitions

• Text Book:Text Book: M. T. Goodrich and R. Tamassia, "Data M. T. Goodrich and R. Tamassia, "Data Structures and Algorithms in Java," 4th edition, 2006, Wiley Structures and Algorithms in Java," 4th edition, 2006, Wiley

& Sons, Inc., ISBN 978-0471738848& Sons, Inc., ISBN 978-0471738848..

Basic DefinitionsBasic Definitions• Data StructuresData Structures::

A data structure is a systematic way of A data structure is a systematic way of organizingorganizing and and accessingaccessing data. Or, It’s the data. Or, It’s the logicallogical relationship between data elements. relationship between data elements.

• Types of Data Structures:Types of Data Structures:

- Linear D.S., such as arrays, stacks, queues.- Linear D.S., such as arrays, stacks, queues.- Non-linear D.S., such as tree.- Non-linear D.S., such as tree.

• Arrays:Arrays:

An array is a numbered (An array is a numbered (indexedindexed) collection ) collection of variables, all of the of variables, all of the samesame type. type.

• Storage StructureStorage Structure::

It is the It is the physicalphysical (actual) representation of (actual) representation of data elements in storage (memory).data elements in storage (memory).

• Types of Storage Structures:Types of Storage Structures:

1- 1- Sequential S.S.Sequential S.S.

(Suitable for storage of (Suitable for storage of staticstatic D.S. such D.S. such as as arrays) arrays)

2- 2- Linked S.S.Linked S.S.

(Suitable for storage of (Suitable for storage of dynamicdynamic D.S.) D.S.)

Object Oriented ApproachObject Oriented Approach

One of the main ideas of the object-One of the main ideas of the object-oriented approach is that: oriented approach is that: datadata should should be presented as being be presented as being encapsulatedencapsulated with with methodsmethods (functions) that (functions) that accessaccess and and modifymodify data. data.

ADT (Abstract Data Type):ADT (Abstract Data Type):It is a It is a mathematicalmathematical modelmodel of a data structure that specifies of a data structure that specifies the following:the following:

- the - the TypeType of data stored, of data stored, - the - the OperationsOperations performedperformed (supported) on (supported) on

them, andthem, and- the - the TypesTypes of of ParametersParameters of these operations. of these operations.

An ADT is modeled in Java by a An ADT is modeled in Java by a classclass..

Abstraction:Abstraction:

An ADT specifies An ADT specifies whatwhat each operation does, but each operation does, but not not howhow it does it.it does it.

• ClassesClasses::

A class defines the A class defines the datadata being being storedstored and and operationsoperations supported supported by the by the objectsobjects..

• ObjectsObjects::

An An objectobject is an is an instance instance of the of the class.class.Objects in Java: store Objects in Java: store datadata and provide and provide methodsmethods for for accessingaccessing and and modifyingmodifying this data. this data.

• InterfacesInterfaces::

An An interfaceinterface is simply a list of is simply a list of methodmethod declarationsdeclarations, where , where each method has an empty body.each method has an empty body.

Unlike an interface, classes specify Unlike an interface, classes specify howhow the operations are the operations are performed in the body of each method.performed in the body of each method.

• AlgorithmAlgorithm

An An algorithmalgorithm is a is a step-by-stepstep-by-step procedureprocedure for performing for performing some some tasktask in a in a finitefinite amount of time. amount of time.

• Pseudo CodePseudo Code

An algorithm is An algorithm is writtenwritten (expressed) in a mixture of Natural (expressed) in a mixture of Natural languages and High-level programming languages, this is languages and High-level programming languages, this is called called pseudopseudo code code..

• ProgramProgram

A program is the A program is the implementationimplementation (translation) of an algorithm (translation) of an algorithm in some high-level programming language.in some high-level programming language.

1.5. Arrays1.5. Arrays• ArrayArray: is a : is a numberednumbered collection of collection of

variables, all of the variables, all of the samesame type of data, or type of data, or it’s a set of it’s a set of indexedindexed variables. variables.

• ArraysArrays are special kinds of objects, so we are special kinds of objects, so we can use can use newnew operator to create a new operator to create a new instance of an array.instance of an array.

• CellsCells: each variable or : each variable or cellcell in an array has in an array has an an indexindex, which uniquely refers to the value , which uniquely refers to the value stored in that cell. Cells of an array are stored in that cell. Cells of an array are numbered 0, 1, 2, …. etc.numbered 0, 1, 2, …. etc.

• We use arrays to store a numbered group of related objects. We use arrays to store a numbered group of related objects. • Example 1Example 1: To store : To store top tentop ten scores of a game. scores of a game.

Instead of using a different Instead of using a different single variablesingle variable to store each to store each score, we use a single object to store score, we use a single object to store allall group of scores, group of scores, and each score will be referred to using and index, or and each score will be referred to using and index, or subscript.subscript.

• Example 2Example 2: To store medical information system of : To store medical information system of patients currently assigned to beds in a certain hospital. patients currently assigned to beds in a certain hospital. Instead of using 200 different variables, we use one group Instead of using 200 different variables, we use one group and refer to each patient’s information by an index.and refer to each patient’s information by an index.

Use of Arrays:

Arrays: DeclarationArrays: Declaration

• An array stores multiple values of the same An array stores multiple values of the same type.type.

• If the type is a primitive typeIf the type is a primitive type, , each element each element contains one value of the declared type.contains one value of the declared type.

boolean[] flags;boolean[] flags; //declare flags as a Boolean array //declare flags as a Boolean array (object) (object)

Here, no memory space is allocated for storing object Here, no memory space is allocated for storing object flags.flags.flagsflags is a name (or reference) to an array of integers. is a name (or reference) to an array of integers.

Memory Allocation for ArraysMemory Allocation for Arrays flags = new boolean[20];flags = new boolean[20]; // Allocates an array // Allocates an array flagsflags in in

memory memory

flags = new boolean[10]; flags = new boolean[10]; // now // now flagsflags is reference to is reference to another array another array

int[] grades = new int[12];int[] grades = new int[12]; // declare variable grades; create // declare variable grades; create an array; make an array; make gradesgrades a a reference of this array reference of this array

int grades2[]; int grades2[]; // a less readable format// a less readable format

Arrays: ElementsArrays: Elements• Refer to particular element in the array by Refer to particular element in the array by positionposition

number (called index)number (called index)int[] grades = new int[12];int[] grades = new int[12];

grades[2] = 10;grades[2] = 10;

• The index starts from The index starts from 00; thus the index value must be ; thus the index value must be between 0 to N-1, where N is the between 0 to N-1, where N is the lengthlength of the array of the array

• For example, for the preceding array For example, for the preceding array gradesgrades, it can be , it can be indexed only using the numbers 0 to 11indexed only using the numbers 0 to 11

Array: An Array of ValuesArray: An Array of Values

A 12-element array of values.

-45

6

0

72

1543

-89

0

62

-3

1

6453

-78grades[ 11 ]

grades[ 10 ]

grades[ 9 ]

grades[ 8]

grades[ 7 ]

grades[ 4 ]

grades[ 3 ]

grades[ 2 ]

grades[ 1 ]

grades[ 0 ]

grades[ 6 ]

grades[ 5 ]

position number (index or subscript) of the element within array grades

grades

int[] grades = new int[12];grades[0] = -45;…grades[11] = -78;

Arrays: DeclarationArrays: Declaration• An array can also store multiple An array can also store multiple objectsobjects: each : each

element of the array is a element of the array is a referencereference to an object to an object of the declared typeof the declared type

Month[] months;Month[] months;

months = new Month[12];months = new Month[12];

String[] codes = new String[26];String[] codes = new String[26];

Array: An Array of ObjectsArray: An Array of Objects

A 12-element array of Month objects

ref to obj 0

ref to obj 1

ref to obj 2

ref to obj 3

ref to obj 4

ref to obj 5

ref to obj 6

ref to obj 7

ref to obj 8

ref to obj 9months[ 9 ]

months[ 8]

months[ 7 ]

months[ 4 ]

months[ 3 ]

months[ 2 ]

months[ 1 ]

months[ 0 ]

months[ 6 ]

months[ 5 ]

position number (index or subscript) of the element within array months

months

ref to obj 10months[ 10 ]

ref to obj 11months[ 11 ]

Month[] months;months = new Month[12];for (int i = 0; i < 12; i++) months[i] = new Month(i+1,2005);

Shortcut: Array Initializer ListShortcut: Array Initializer List• An An initializer listinitializer list can be used to instantiate and initialize an can be used to instantiate and initialize an

array in one steparray in one step• The values are delimited by braces and separated by commasThe values are delimited by braces and separated by commas

– allocate space for the array allocate space for the array –– number of elements in number of elements in initializer list determines the size of arrayinitializer list determines the size of array

– elements in array are initialized with the values in the elements in array are initialized with the values in the initializer listinitializer list

• The The newnew operator is not used operator is not used Examples:Examples: int[] units = {147, 323, 89, 933, 540};int[] units = {147, 323, 89, 933, 540};

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

String[] wordList = {“cs112“, “computer", “elevision"};String[] wordList = {“cs112“, “computer", “elevision"}; Month[] longMonths = {new Month(1, 2005), new Month(3, 2005), Month[] longMonths = {new Month(1, 2005), new Month(3, 2005), new Month(5, 2005), new Month(7, 2005), new Month(8, 2005), new Month(5, 2005), new Month(7, 2005), new Month(8, 2005), new Month(10, 2005), new Month(12, 2005) }; new Month(10, 2005), new Month(12, 2005) };

Shortcut: Enumerate Array Shortcut: Enumerate Array ElementsElements

•There is a special There is a special forfor statement statement to to enumerateenumerate array elements: array elements:

Example:Example: int[] primes = {2, 3, 5, 7, 11};int[] primes = {2, 3, 5, 7, 11};

for (int i : primes)for (int i : primes) System.out.println ( i + “ “); System.out.println ( i + “ “);

Arrays as ObjectsArrays as Objects

• In Java, an array is considered as an In Java, an array is considered as an objectobject

Implication:Implication:– has attributes: e.g., the has attributes: e.g., the lengthlength attribute. attribute.

– parameter passing will be the same as parameter passing will be the same as object.object.

– Array name is a reference to the place of Array name is a reference to the place of memory in which the array is stored.memory in which the array is stored.

2121

Array: Array: lengthlength• Each array has a public Each array has a public constantconstant called called lengthlength that stores the size of the array that stores the size of the array– once an array is created, it has a fixed sizeonce an array is created, it has a fixed size– we will see ArrayList, a dynamic array next we will see ArrayList, a dynamic array next

class.class.

• It is referenced using the array name (just It is referenced using the array name (just like any other object):like any other object):

grades.lengthgrades.length

• Note that Note that lengthlength holds the number of holds the number of elements, elements, notnot the largest index, e.g. the largest index, e.g.for (int index=0; index < grades.length; index++)

grades[index] = scan.nextInt();

Arrays as ParametersArrays as Parameters

• An entire array can be passed to a method as a An entire array can be passed to a method as a parameter:parameter:– like any other object, the like any other object, the referencereference to the array is passed, to the array is passed,

making the formal and actual parameters aliases of each making the formal and actual parameters aliases of each other.other.

– changing an array element in the method changes the changing an array element in the method changes the original.original.

• An array element can be passed to a method as well, An array element can be passed to a method as well, and follow the parameter passing rules of that and follow the parameter passing rules of that element's typeelement's type

Calling a Method: Array Calling a Method: Array ReferenceReference

static void doubleArray (int[] array)

doubleArray( array );

int[] array = {1, 2, 3}; array

array

123

246

{ for (int i = 0; i < array.length; i++) array[i] *= 2;

}

i

• Each time a method is called, the Each time a method is called, the actual argumentsactual arguments in the in the invocation are copied into the invocation are copied into the formal argumentsformal arguments– if a if a valuevalue type, then it is the type, then it is the valuevalue that is copied that is copied– if a if a referencereference type, then it is the type, then it is the referencereference that is copied that is copied

• The formal argument and the actual argument are The formal argument and the actual argument are differentdifferent variables, with different memory locations.variables, with different memory locations.

2468

array = new int[ ] {2, 4, 6, 8};

Example: Using the Example: Using the Elements of an Array as Elements of an Array as CountersCounters• Use array elements to keep track of Use array elements to keep track of

number of occurrences of different valuesnumber of occurrences of different values– create an array with size of the number of create an array with size of the number of

possible valuespossible values

– each element of the array keeps track of the each element of the array keeps track of the number of occurrences of one valuenumber of occurrences of one value

– when a possibility occurs, increase the array when a possibility occurs, increase the array element by oneelement by one• may need to map from value to indexmay need to map from value to index

Example: Using the Example: Using the Elements of an Array as Elements of an Array as CountersCounters• Read a sequence of integers between 1 to 10 Read a sequence of integers between 1 to 10

until user inputs 0; keep track of number of until user inputs 0; keep track of number of occurrences of 1 to 10:occurrences of 1 to 10:int[] counters = new int[10];int[] counters = new int[10];int num;int num;while ( (num=scan.nextInt()) != 0)while ( (num=scan.nextInt()) != 0) counters[num-1]++; counters[num-1]++;

• Count the number of lower-case characters in a Count the number of lower-case characters in a line:line:

int[] counters = new int[26];int[] counters = new int[26];String line = scan.nextLine();String line = scan.nextLine();for (int i = 0; i < line.length(); i++) {for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); char ch = line.charAt(i); if (‘a’ <= ch && ch <= ‘z’) if (‘a’ <= ch && ch <= ‘z’) counters[ counters[ch-’a’ch-’a’]++;]++;

Cloning an ArrayCloning an Array• double[ ] a;double[ ] a;• double[ ] b; double[ ] b; a = new double[10]; a = new double[10]; // Allocates an array flags in memory

b = a; b = a; // // here both a and b refer to the same array

b[3] = 5;b[3] = 5; // this is equivalent to setting a[3] to 5

• If instead, If instead, we want to create an exact we want to create an exact copycopy of the array, a , of the array, a , and assign the array variable and assign the array variable bb to this copy of array a, we to this copy of array a, we write:write:b = a.clone();b = a.clone(); // copies all cells of a into a new array and

assigns b to point to that arrayb[3] = 5;b[3] = 5; // the new copied array will have its cell at

index 3 assigned the value 5, but the cell a[3] doesn’t change

Array InitializationArray Initialization

•Arrays of Arrays of Basic TypesBasic Types (primitive data types) are (primitive data types) are initialized to initialized to zeroszeros..

•Arrays of Arrays of ObjectsObjects are are initialized to initialized to nullnull referencesreferences..

Out of Bounds ErrorOut of Bounds Error

• An attempt to access an array An attempt to access an array

element indexed by a number element indexed by a number

outside the range outside the range 00 and and a.lenght – 1a.lenght – 1, ,

such a reference is said to be such a reference is said to be out-of-out-of-

boundsbounds error condition (exception). error condition (exception).

3.1. Using Arrays3.1. Using Arrays• Arrays can be used to store high score Arrays can be used to store high score

entries for a video game. entries for a video game.

• In this case, we use an array of In this case, we use an array of objectsobjects, ,

each contains two fields: each contains two fields: scorescore and and

namename..

• Initially, this array stores only Initially, this array stores only nullnull entries entries

(references).(references).

• As users this game, we fill array cells As users this game, we fill array cells

with with referencesreferences to new objects. to new objects.

Methods for Updating Methods for Updating ArraysArrays• We will have to define methods for We will have to define methods for

updating entries of arrays.updating entries of arrays.1.1. InsertionInsertion

One of the most common updates we One of the most common updates we might need to apply to arrays is to add a might need to apply to arrays is to add a new game entry.new game entry.add(e):add(e): Inserts game entry e into the collection of high scores. If the array is full, e is added only if its score is higher than the lowest score in the set, and in this case, e replaces the entry with the lowest score.

The main challenge in insertion is to The main challenge in insertion is to make make roomroom for e. for e. see code fragment 3.3. see code fragment 3.3.

2.2. DeletionDeletion We must define a method that lets us remove a We must define a method that lets us remove a

game entry from the array. This means to game entry from the array. This means to delete a reference to a game entry object from delete a reference to a game entry object from array entries.array entries.

remove(e):remove(e): Removes and returns the entry e at index i in the array. If index i is outside the bounds of array entries, this method throws an exception, otherwise, object at index object at index i will be will be removed, and all following objects will be removed, and all following objects will be “moved over” to fill the empty cell.“moved over” to fill the empty cell.

We start from index We start from index i and move all references at and move all references at indices higher than indices higher than i one cell to left, code 3.4. one cell to left, code 3.4.

3.3. Sorting an ArraySorting an ArrayHere, we start with an array of objects Here, we start with an array of objects that are out of order and we need to that are out of order and we need to put them in order, which is known as put them in order, which is known as the the sortingsorting problem. problem.

• Simple Insertion Sort AlgorithmSimple Insertion Sort AlgorithmAlgorithmAlgorithm InsertioSort(A): InsertioSort(A):

Input:Input: An array A of n comparable elements. An array A of n comparable elements.Output:Output: The array A with elements The array A with elements

rearranged in rearranged in ascending order ascending orderfor for i i ←← 1 1 to to n-1n-1 do do Insert A[i] at its proper location in A[0], A[1], …, A[i-Insert A[i] at its proper location in A[0], A[1], …, A[i-

1]1]

High-level description of Insertion Sort Algorithm

3434

Detail of Insertion SortDetail of Insertion Sort

AlgorithmAlgorithm InsertioSort(A): InsertioSort(A):Input:Input: An array A of n comparable elements. An array A of n comparable elements.Output:Output: The array A with elements The array A with elements

rearranged in rearranged in ascending order ascending order for for i i ←← 1 1 to n-1 do to n-1 do

curcur ← ← A[i] A[i]

j j ← ← i-1i-1 while j ≥ 0 and A[j] > cur dowhile j ≥ 0 and A[j] > cur do

A[j+1] A[j+1] ← ← A[j]A[j]j ← j-1j ← j-1A[j+1] A[j+1] ← ← curcur {cur is now the right place}{cur is now the right place}

Intermediate-level description of InsertionSort Algorithm

3636

Some Simple Methods of Some Simple Methods of java.util.Arraysjava.util.Arrays    equals(A, B):equals(A, B): Returns true if and only if the array A and

the array B are equal. • they have the same number of elements • every corresponding pair of elements in the two arrays are equal.

    

 fill(A,x):fill(A,x): Stores element x into every cell of array A.

     sort(A):sort(A): Sorts the array A using the natural ordering of its elements.

     toString(A):toString(A): Returns a String representation of the array A.

For example, the following string would be returned by the method toString called on an array of integers A = [4,5,2,3,5,7,10]:

          [4, 5, 2, 3, 5, 7, 10]

3737

new String(A)new String(A) create an object of class String from a character array A

For example, the string we would construct from the array A = [a, c, a, t] is acat.

 S.toCharArray()S.toCharArray() create a character array representation of S

For example, if we call toCharArray on the string adog, we would get the array B = [a, d, o, g].

Simple Cryptography with Strings and Simple Cryptography with Strings and Character ArraysCharacter Arrays

3838

Two-Dimensional ArraysTwo-Dimensional Arrays• A A one-dimensionalone-dimensional array array stores a simple list of values. stores a simple list of values.

• A A two-dimensionaltwo-dimensional array array can be thought of as a can be thought of as a tabletable of values, of values, with with rowsrows and and columns.columns.

• A two-dimensional array element is referenced using two index A two-dimensional array element is referenced using two index values values , , say i and j. The first index usually refers to a row say i and j. The first index usually refers to a row number and the second to a column number. number and the second to a column number.

• To be precise, a two-dimensional array in Java is an array of To be precise, a two-dimensional array in Java is an array of

arrays, that is an array with each of its cells being another array.arrays, that is an array with each of its cells being another array. • Array is sometimes also called a matrixArray is sometimes also called a matrix

Two-Dimensional ArraysTwo-Dimensional Arrays

A rectangle two-dimensional array with three rows and four columns.

Row 0

Row 1

Row 2

Column 1Column 0 Column 2 Column 3

a[0][0] a[0][3]a[0][1] a[0][2]

a[1][0] a[1][3]a[1][1] a[1][2]

a[2][0] a[2][3] a[2][2]

Column index (or subscript)

Row index (or subscript)

Array name

a [2][1]

4040

Two-dimensional Arrays: Two-dimensional Arrays: InitializerInitializer

• An initializer list can be used to create and set up An initializer list can be used to create and set up a two-dimensional array.a two-dimensional array.

• Each element in the list is itself an initializer list.Each element in the list is itself an initializer list.

• Each array dimension has its own Each array dimension has its own lengthlength constant.constant.

Initializer: ExampleInitializer: Example

public class Test2DArray{ public static void main(String[] args) { int[][] days = { {1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {0} }; for (int i = 0; i < days.length; i++) { for (int j = 0; j < days[i].length; j++) System.out.print( days[i][j] ); System.out.println (); } }}

4242

2D arrays: Declaration2D arrays: Declaration

• In Java, we declare a 2D array as follows:In Java, we declare a 2D array as follows:•                     intint[][] Y = [][] Y = new intnew int[8][10][8][10]

– 2D array having 8 rows and 10 columns. 2D array having 8 rows and 10 columns. – That is, Y is an array of length 8 such that each element of Y is That is, Y is an array of length 8 such that each element of Y is

an array of length 10 of integers. an array of length 10 of integers.

4343

Tic-Tac-ToeTic-Tac-Toe• tic-tac-toe is a game played in a three-by-three board.tic-tac-toe is a game played in a three-by-three board.

• Two players—X and O—alternate in placing their respective marks in the Two players—X and O—alternate in placing their respective marks in the cells of this board, starting with player X. If either player succeeds in getting cells of this board, starting with player X. If either player succeeds in getting three of his or her marks in a row, column, or diagonal, then that player wins.three of his or her marks in a row, column, or diagonal, then that player wins.

• 11 indicating an X, and indicating an X, and −1−1 indicating O. indicating O.

• This encoding allows us to have a simple way of testing if a given board This encoding allows us to have a simple way of testing if a given board configuration is a win for X or O, namely, if the values of a row, column, or configuration is a win for X or O, namely, if the values of a row, column, or diagonal add up to −3 or 3. diagonal add up to −3 or 3.

4444

Multidimensional ArraysMultidimensional Arrays• An array can have as many dimensions as An array can have as many dimensions as

needed, creating a multidimensional array.needed, creating a multidimensional array.

• Each dimension subdivides the previous one Each dimension subdivides the previous one into the specified number of elements.into the specified number of elements.

• Each array dimension has its own Each array dimension has its own lengthlength constant.constant.

• Because each dimension is an array of array Because each dimension is an array of array references, the arrays within one dimension references, the arrays within one dimension could be of different could be of different lengthslengths..