Download presentation
Presentation is loading. Please wait.
Published byApril Hunt Modified over 9 years ago
1
Text Book: M. T. Goodrich and R. Tamassia, "Data Structures and Algorithms in Java," 4th edition, 2006, Wiley & Sons, Inc., ISBN 978-0471738848. Text Book: M. T. Goodrich and R. Tamassia, "Data Structures and Algorithms in Java," 4th edition, 2006, Wiley & Sons, Inc., ISBN 978-0471738848.
4
Basic Definitions Data Structures: Data Structures: A data structure is a systematic way of organizing and accessing data. Or, It’s the logical relationship between data elements. A data structure is a systematic way of organizing and accessing data. Or, It’s the logical relationship between data elements. Types of Data Structures: Types of Data Structures: - Linear D.S., such as arrays, stacks, queues. - Non-linear D.S., such as tree. Arrays: Arrays: An array is a numbered (indexed) collection of variables, all of the same type.
5
Storage Structure: Storage Structure: It is the physical (actual) representation of data elements in storage (memory). Types of Storage Structures: Types of Storage Structures: 1- Sequential S.S. (Suitable for storage of static D.S. such as arrays) (Suitable for storage of static D.S. such as arrays) 2- Linked S.S. (Suitable for storage of dynamic D.S.)
6
Object Oriented Approach Object Oriented Approach One of the main ideas of the object- oriented approach is that: data should be presented as being encapsulated with methods (functions) that access and modify data. One of the main ideas of the object- oriented approach is that: data should be presented as being encapsulated with methods (functions) that access and modify data.
7
ADT (Abstract Data Type): It is a mathematical model of a data structure that specifies the following: - the Type of data stored, - the Operations performed (supported) on them, and - the Types of Parameters of these operations. An ADT is modeled in Java by a class. Abstraction: An ADT specifies what each operation does, but not how it does it.
8
Classes: Classes: A class defines the data being stored and operations supported by the objects. Objects : Objects : An object is an instance of the class. Objects in Java: store data and provide methods for accessing and modifying this data. Interfaces : Interfaces : An interface is simply a list of method declarations, where each method has an empty body. Unlike an interface, classes specify how the operations are performed in the body of each method.
9
Algorithm Algorithm An algorithm is a step-by-step procedure for performing some task in a finite amount of time. An algorithm is a step-by-step procedure for performing some task in a finite amount of time. Pseudo Code Pseudo Code An algorithm is written (expressed) in a mixture of Natural languages and High-level programming languages, this is called pseudo code. Program Program A program is the implementation (translation) of an algorithm in some high-level programming language.
10
1.5. Arrays Array: is a numbered collection of variables, all of the same type of data, or it’s a set of indexed variables. Array: is a numbered collection of variables, all of the same type of data, or it’s a set of indexed variables. Arrays are special kinds of objects, so we can use new operator to create a new instance of an array. Arrays are special kinds of objects, so we can use new operator to create a new instance of an array. Cells: each variable or cell in an array has an index, which uniquely refers to the value stored in that cell. Cells of an array are numbered 0, 1, 2, …. etc. Cells: each variable or cell in an array has an index, which uniquely refers to the value stored in that cell. Cells of an array are numbered 0, 1, 2, …. etc.
11
We use arrays to store a numbered group of related objects. We use arrays to store a numbered group of related objects. Example 1: To store top ten scores of a game. Example 1: To store top ten scores of a game. Instead of using a different single variable to store each score, we use a single object to store all group of scores, and each score will be referred to using and index, or subscript. Example 2: To store medical information system of patients currently assigned to beds in a certain hospital. Instead of using 200 different variables, we use one group and refer to each patient’s information by an index. Example 2: To store medical information system of patients currently assigned to beds in a certain hospital. Instead of using 200 different variables, we use one group and refer to each patient’s information by an index. Use of Arrays:
12
Arrays: Declaration An array stores multiple values of the same type. An array stores multiple values of the same type. If the type is a primitive type, each element contains one value of the declared type. If the type is a primitive type, each element contains one value of the declared type. boolean[] flags; //declare flags as a Boolean array (object) boolean[] flags; //declare flags as a Boolean array (object) Here, no memory space is allocated for storing object flags. flags is a name (or reference) to an array of integers.
13
Memory Allocation for Arrays flags = new boolean[20]; // Allocates an array flags in memory flags = new boolean[20]; // Allocates an array flags in memory flags = new boolean[10]; // now flags is reference to another array flags = new boolean[10]; // now flags is reference to another array int[] grades = new int[12]; // declare variable grades; create an array; make grades a reference of this array int[] grades = new int[12]; // declare variable grades; create an array; make grades a reference of this array int grades2[]; // a less readable format int grades2[]; // a less readable format
14
Arrays: Elements Refer to particular element in the array by position number (called index) Refer to particular element in the array by position number (called index) int[] grades = new int[12]; grades[2] = 10; The index starts from 0; thus the index value must be between 0 to N-1, where N is the length of the array The index starts from 0; thus the index value must be between 0 to N-1, where N is the length of the array For example, for the preceding array grades, it can be indexed only using the numbers 0 to 11 For example, for the preceding array grades, it can be indexed only using the numbers 0 to 11
15
Array: An Array of Values A 12-element array of values. -45 6 0 72 1543 -89 0 62 -3 1 6453 -78 grades[ 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;
16
Arrays: Declaration An array can also store multiple objects: each element of the array is a reference to an object of the declared type An array can also store multiple objects: each element of the array is a reference to an object of 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];
17
Array: 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);
18
Shortcut: Array Initializer List An initializer list can be used to instantiate and initialize an array in one step An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas The values are delimited by braces and separated by commas –allocate space for the array – number of elements in initializer list determines the size of array –elements in array are initialized with the values in the initializer list The new operator is not used The new 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"}; Month[] longMonths = {new Month(1, 2005), new Month(3, 2005), new Month(5, 2005), new Month(7, 2005), new Month(8, 2005), new Month(10, 2005), new Month(12, 2005) }; String[] wordList = {“cs112“, “computer", “elevision"}; Month[] longMonths = {new Month(1, 2005), new Month(3, 2005), new Month(5, 2005), new Month(7, 2005), new Month(8, 2005), new Month(10, 2005), new Month(12, 2005) };
19
Shortcut: Enumerate Array Elements There is a special for statement to enumerate array elements: There is a special for statement to enumerate array elements: Example: Example: int[] primes = {2, 3, 5, 7, 11}; int[] primes = {2, 3, 5, 7, 11}; for (int i : primes) System.out.println ( i + “ “); for (int i : primes) System.out.println ( i + “ “);
20
Arrays as Objects In Java, an array is considered as an object In Java, an array is considered as an objectImplication: –has attributes: e.g., the length attribute. –parameter passing will be the same as object. –Array name is a reference to the place of memory in which the array is stored.
21
21 Array: length Each array has a public constant called length that stores the size of the array Each array has a public constant called length that stores the size of the array –once an array is created, it has a fixed size –we will see ArrayList, a dynamic array next class. It is referenced using the array name (just like any other object): It is referenced using the array name (just like any other object): grades.length grades.length Note that length holds the number of elements, not the largest index, e.g. Note that length holds the number of elements, not the largest index, e.g. for (int index=0; index < grades.length; index++) grades[index] = scan.nextInt();
22
Arrays as Parameters An entire array can be passed to a method as a parameter: An entire array can be passed to a method as a parameter: – like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other. – changing an array element in the method changes the original. An array element can be passed to a method as well, and follow the parameter passing rules of that element's type An array element can be passed to a method as well, and follow the parameter passing rules of that element's type
23
Calling a Method: Array Reference static void doubleArray (int[] array) doubleArray( array ); int[] array = {1, 2, 3}; array 1 2 3 2 4 6 { for (int i = 0; i < array.length; i++) array[i] *= 2; } i Each time a method is called, the actual arguments in the invocation are copied into the formal arguments Each time a method is called, the actual arguments in the invocation are copied into the formal arguments –if a value type, then it is the value that is copied –if a reference type, then it is the reference that is copied The formal argument and the actual argument are different variables, with different memory locations. The formal argument and the actual argument are different variables, with different memory locations. 2 4 6 8 array = new int[ ] {2, 4, 6, 8};
24
Example: Command-Line Arguments The signature of the main method indicates that it takes an array of String objects as a parameter The signature of the main method indicates that it takes an array of String objects as a parameter These values come from command-line arguments that are provided when the interpreter is invoked These values come from command-line arguments that are provided when the interpreter is invoked For example, the following invocation of the interpreter passes an array of two String objects into main method: For example, the following invocation of the interpreter passes an array of two String objects into main method: > java NameTag Howdy John The strings “ Howdy ” and “ John ” are stored at indexes 0- 1 of the String array args The strings “ Howdy ” and “ John ” are stored at indexes 0- 1 of the String array args
25
Example: Using the Elements of an Array as Counters Use array elements to keep track of number of occurrences of different values Use array elements to keep track of number of occurrences of different values –create an array with size of the number of possible values –each element of the array keeps track of the number of occurrences of one value –when a possibility occurs, increase the array element by one may need to map from value to index may need to map from value to index
26
Example: Using the Elements of an Array as Counters Read a sequence of integers between 1 to 10 until user inputs 0; keep track of number of occurrences of 1 to 10: int[] counters = new int[10]; int num; while ( (num=scan.nextInt()) != 0) counters[num-1]++; Read a sequence of integers between 1 to 10 until user inputs 0; keep track of number of occurrences of 1 to 10: int[] counters = new int[10]; int num; while ( (num=scan.nextInt()) != 0) counters[num-1]++; Count the number of lower-case characters in a line: int[] counters = new int[26]; String line = scan.nextLine(); for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (‘a’ <= ch && ch <= ‘z’) counters[ch-’a’]++; Count the number of lower-case characters in a line: int[] counters = new int[26]; String line = scan.nextLine(); for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (‘a’ <= ch && ch <= ‘z’) counters[ch-’a’]++;
27
Cloning 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, we want to create an exact copy of the array, a, and assign the array variable b to this copy of array a, we write: If instead, we want to create an exact copy of the array, a, and assign the array variable b to this copy of array a, we write: b = a.clone(); b = a.clone(); // copies all cells of a into a new array and assigns b to point to that array b[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
28
Array Initialization Arrays of Basic Types (primitive data types) are initialized to zeros. Arrays of Basic Types (primitive data types) are initialized to zeros. Arrays of Objects are initialized to null references. Arrays of Objects are initialized to null references.
29
Out of Bounds Error An attempt to access an array element indexed by a number outside the range 0 and a.lenght – 1, such a reference is said to be out-of-bounds error condition (exception). An attempt to access an array element indexed by a number outside the range 0 and a.lenght – 1, such a reference is said to be out-of-bounds error condition (exception).
30
3.1. Using Arrays Arrays can be used to store high score entries for a video game. Arrays can be used to store high score entries for a video game. In this case, we use an array of objects, each contains two fields: score and name. In this case, we use an array of objects, each contains two fields: score and name. Initially, this array stores only null entries (references). Initially, this array stores only null entries (references). As users this game, we fill array cells with references to new objects. As users this game, we fill array cells with references to new objects.
31
Methods for Updating Arrays We will have to define methods for updating entries of arrays. We will have to define methods for updating entries of arrays. 1. Insertion One of the most common updates we might need to apply to arrays is to add a 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 make room for e. see code fragment 3.3. The main challenge in insertion is to make room for e. see code fragment 3.3.
32
2. Deletion We must define a method that lets us remove a game entry from the array. This means to delete a reference to a game entry object from array entries. We must define a method that lets us remove a game entry from the array. This means to delete a reference to a game entry object from array entries. remove(e): object at index will be removed, and all following objects will be “moved over” to fill the empty cell. 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 i will be removed, and all following objects will be “moved over” to fill the empty cell. We start from index and move all references at indices higher than one cell to left, code 3.4. We start from index i and move all references at indices higher than i one cell to left, code 3.4.
33
3. Sorting an Array Here, we start with an array of objects that are out of order and we need to put them in order, which is known as the sorting problem. Simple Insertion Sort Algorithm Simple Insertion Sort Algorithm Algorithm InsertioSort(A): Input: An array A of n comparable elements. Output: The array A with elements rearranged in ascending order for i ← 1 to n-1 do Insert A[i] at its proper location in A[0], A[1], …, A[i-1] Insert A[i] at its proper location in A[0], A[1], …, A[i-1] High-level description of Insertion Sort Algorithm
34
34
35
Detail of Insertion Sort Algorithm InsertioSort(A): Input: An array A of n comparable elements. Output: The array A with elements rearranged in ascending order for i ← 1 to n-1 do for i ← 1 to n-1 do cur ← A[i] cur ← A[i] j ← i-1 j ← i-1 while j ≥ 0 and A[j] > cur do while j ≥ 0 and A[j] > cur do A[j+1] ← A[j] j ← j-1 A[j+1] ← cur{cur is now the right place} Intermediate-level description of InsertionSort Algorithm
36
36 Some Simple Methods of java.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]
37
37 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 Character Arrays
38
38 Two-Dimensional Arrays A one-dimensional array stores a simple list of values. A one-dimensional array stores a simple list of values. A two-dimensional array can be thought of as a table of values, with rows and columns. A two-dimensional array can be thought of as a table of values, with rows and columns. A two-dimensional array element is referenced using two index values, say i and j. The first index usually refers to a row number and the second to a column number. A two-dimensional array element is referenced using two index values, say i and j. The first index usually refers to a row number and the second to a column number. 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. 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. Array is sometimes also called a matrix Array is sometimes also called a matrix
39
Two-Dimensional Arrays A rectangle two-dimensional array with three rows and four columns. Row 0 Row 1 Row 2 Column 1Column 0Column 2Column 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]
40
40 Two-dimensional Arrays: Initializer An initializer list can be used to create and set up a two-dimensional array. An initializer list can be used to create and set up 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 length constant. Each array dimension has its own length constant.
41
Initializer: 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 (); } } }
42
42 2D arrays: Declaration In Java, we declare a 2D array as follows: In Java, we declare a 2D array as follows: int[][] Y = new int[8][10] int[][] Y = new int[8][10] –2D array having 8 rows and 10 columns. –That is, Y is an array of length 8 such that each element of Y is an array of length 10 of integers.
43
43 Tic-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 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. 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 three of his or her marks in a row, column, or diagonal, then that player wins. 1 indicating an X, and −1 indicating O. 1 indicating an X, and −1 indicating O. 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 diagonal add up to −3 or 3. 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 diagonal add up to −3 or 3.
44
44 Multidimensional Arrays An array can have as many dimensions as needed, creating a multidimensional array. An array can have as many dimensions as needed, creating a multidimensional array. Each dimension subdivides the previous one into the specified number of elements. Each dimension subdivides the previous one into the specified number of elements. Each array dimension has its own length constant. Each array dimension has its own length constant. Because each dimension is an array of array references, the arrays within one dimension could be of different lengths. Because each dimension is an array of array references, the arrays within one dimension could be of different lengths.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.