Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.

Similar presentations


Presentation on theme: "Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage."— Presentation transcript:

1 Dr. Sahar Shabanah Lecture 3: Arrays

2 Data Structures Data structures are organized collections of information and a set of operations used to manage that information Data Structures Classifications Linear / Non-Linear Data Structures: Linear data structure: maintains a linear relationship between its elements Ex: an array holds the linear relationship between its elements Non-linear data structure: does not maintain any linear relationship between its elements. Ex: Trees 2

3 Data Structures Static / Dynamic data structure Static data structure has a fixed size Ex: Arrays; once defined, the number of elements it can hold doesn’t change Dynamic data structure grows and shrinks at execution time as required by its contents Ex: Linked Lists, trees Data structures should be abstractions: hide unneeded details separate the interface of the structure from its underlying implementation to manage complexity, change the implementation without changing the interface 3

4 Abstract Data Types (ADT) It is the mathematical model of a data structure that specifies the following: Types of the data stored, Operations performed (ADT Interface) on them, and Types of parameters of these operations Objects are a perfect programming mechanism to create ADTs because their internal details are encapsulated 4

5 Arrays An array is a numbered collection of variables with the same type of data, a set of indexed variables, or an ordered list of values 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9 5

6 Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression: scores[2], refers to the value 94 (3rd value in the array) That expression represents a place to store a single integer and can be used wherever an integer variable can be used For example, an array element can be assigned a value, printed, or used in a calculation : scores[2] = 89; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); 6

7 Arrays The values held in an array are called array elements An array stores multiple values of the same type – the element type The element type can be a primitive type or an object reference Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. In Java, the array itself is an object that must be instantiated scores 79 87 94 82 67 98 87 81 74 91 Another way to depict the scores array: 7

8 Declaring Arrays The scores array could be declared as follows: int[] scores = new int[10]; The type of the variable scores is int[] (an array of integers) Note that the array type does not specify its size, but each object of that type has a specific size The reference variable scores is set to a new array object that can hold 10 integers Other way for array declaration: boolean[] flags; //no memory space is allocated for storing object flags, it is a name or a reference to the array flags = new boolean[20]; //allocate the array flags in memory 8

9 Using Arrays The iterator version of the for loop can be used when processing array elements This is only appropriate when processing all array elements from top (lowest index) to bottom (highest index) for (int score : scores) System.out.println (score); 9

10 Bounds Checking Once an array is created, it has a fixed size An index used in an array reference must specify a valid element, must be between 0 to N-1 An ArrayIndexOutOfBoundsException thrown, if an array index is out of bounds, automatic bounds checking For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 If the value of count is 100, then the following reference will cause an exception to be thrown: System.out.println (codes[count]); 10

11 Bounds Checking It’s common to introduce off-by-one errors when using arrays Each array object has a public constant called length that stores the size of the array It is referenced using the array name: scores.length Note that length holds the number of elements, not the lagest index for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; problem 11

12 Alternate Array Syntax The brackets of the array type can be associated with the element type or with the name of the array Therefore the following two declarations are equivalent: float[] prices; float prices[]; The first format generally is more readable and should be used 12

13 Initializer Lists An initializer list can be used to instantiate and fill an array in one step The values are delimited by braces and separated by commas Example: Note that when an initializer list is used: the new operator is not used no size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can be used only in the array declaration int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; 13

14 Arrays as Objects In Java, an arrays is an object. Implications: has attributes, Ex: length array name is a reference to the place of memory where the array stored. If b=a then a & b refers to the same array, then if b[5]=3; then a[5]=3; Cloning an array b=a.clone(); b is a new array that have a copy of all elements of a 14 a 79 87 94 82 67 98 87 81 74 91 b

15 Arrays as Parameters An entire array can be passed as a parameter to a method Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other Therefore, changing an array element within the method changes the original An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type 15

16 Arrays of Objects The elements of an array can be object references The following declaration reserves space to store 5 references to String objects String[] words = new String[5]; It does NOT create the String objects themselves Initially an array of objects holds null references Each object stored in an array must be instantiated separately 16

17 Arrays of Objects The words array when initially declared: words - - - - - At this point, the following reference would throw a NullPointerException : System.out.println (words[0]); 17

18 Arrays of Objects After some String objects are created and stored in the array: “friendship” words - - “loyalty” “honor” String objects can be created using literals The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep"}; 18

19 Arrays of Objects A UML diagram for the Tunes program: Tunes + main (args : String[]) : void CDCollection - collection : CD[] - count : int - totalCost : double + addCD (title : String, artist : String, cost : double, tracks : int) : void + toString() : String - increaseSize() : void CD - title : String - artist : String - cost : double - tracks : int + toString() : String * 1 19

20 Arrays of Objects The following example manages a collection of CD objects private CD[] collection=new CD[100]; public void addCD (String title, String artist, double cost) { if (count == collection.length) increaseSize(); collection[count] = new CD (title, artist, cost); totalCost += cost; count++; } 20

21 Variable Length Parameter Lists To create a method that processed a different amount of data from one invocation to the next For example, a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75); 1. Define overloaded versions of the average method Downside: we'd need a separate version of the method for each parameter count 21

22 Variable Length Parameter Lists 2. Define the method to accept an array of integers Downside: we'd have to create the array and store the integers prior to calling the method each time Instead, Java provides a convenient way to create variable length parameter lists Using special syntax in the formal parameter list, can define a method to accept any number of parameters of the same type For each call, the parameters are automatically put into an array for easy processing in the method public double average (int... list) { // whatever } element type array name Indicates a variable length parameter list 22

23 Variable Length Parameter Lists public double average (int... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result; } The type of the parameter can be any primitive or object type public void printGrades (Grade... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade);} 23

24 Variable Length Parameter Lists A method that accepts a variable number of parameters can also accept other parameters The varying number of parameters must come last in the formal arguments A single method cannot accept two sets of varying parameters public void test (int count, String name, double... nums) {// whatever} 24

25 Variable Length Parameter Lists Constructors can also be set up to accept a variable number of parameters public class Family { private String[] members;public Family (String... Names) { members = names;} } Public void main() { Family lewis = new Family ("John", "Sharon", "Justin”); Family camden = new Family ("Stephen", "Annie", "Matt", "Mary”, "Simon", "Lucy”); } 25

26 Using Arrays Example Storing Game entries High Scores Class Game entry insertion Game entry removal 26

27 Storing Game entries in an array public class GameEntry { protected String name;// name of the person earning this score protected int score;// the score value /** Constructor to create a game entry */ public GameEntry(String n, int s) { name = n; score = s; } /** Retrieves the name field */ public String getName() { return name; } /** Retrieves the score field */ public int getScore() { return score; } /** Returns a string representation of this entry */ public String toString() { return "(" + name + ", " + score + ")”;} } 27

28 High Scores Class /** Class for storing high scores in an array in non-decreasing order. */ public class Scores { public static final int maxEntries = 10; // number of high scores we keep protected int numEntries;// number of actual entries protected GameEntry[] entries;// array of game entries (names & scores) /** Default constructor */ public Scores() { entries = new GameEntry[maxEntries]; numEntries = 0; } /** Returns a string representation of the high scores list */ public String toString() { String s = "["; for (int i = 0; i < numEntries; i++) { if (i > 0) s += ", "; // separate entries by commas s += entries[i]; } return s + "]"; }....... } 28

29 Game Entry Insertion if entries[] has space: insert e in the right spot; shift things to the right; increment numEntries if entries[] is full: if e is smaller than all scores, do nothing else find the right spot to insert e shift everything to the right one position (thus the last entry is over-written) 29

30 Game Entry Insertion (cont.) public void insert(GameEntry e) { int newScore = e.getScore(); if (numEntries == MAX_ENTRIES) { //if array is full if (newScore < entries[numEntries-1].getScore() return; } else numEntries++; //if we are here, e needs to be inserted; numEntries includes the new entry //start from end and shift entries to the right until finding an entry that’s smaller int i = numEntries-1; while (i > 0 && entry[i-1].getScore() < newScore) { entry[i] = entry[i-1]; i--; } first check i>0check the entry to the left //entry[i-1] is the first entry that’s larger than newScore //entry[i] has been copied to the right, so all we need to do is replace it entry[i] = e; } 30

31 Game Entry Removal remove entry i, if i is outside the bounds, print some error message (or throw an exception) otherwise shift all entries to the right of i one position to the left, and decrement numEntries Public GameEntry remove (int i) throws IndexOutOfBoundsExceptio { if ((i = numEntries)) throw IndexOutOfBoundsException(“invalid index:”+i); GameEntry temp=entries[i]; //if we are here then i is a valid index //shift everything one position to the left; be careful with last element for (int j = i; j < numEntries-1; j++) entries[j] = entries[j+1]; //move to the left entries[numEntries-1]=null; // null out the old last score numEntries--; Return temp; // return the removed object } 31

32 Sorting an array Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) sorting a list of test scores in ascending numeric order sorting a list of people alphabetically by last name There are many algorithms, which vary in efficiency, for sorting a list of items, two specific algorithms: Selection Sort Insertion Sort 32

33 Selection Sort find the smallest value in the list switch it with the value in the first position find the next smallest value in the list switch it with the value in the second position repeat until all values are in their proper places An example: original: 3 9 6 1 2 smallest is 1: 1 9 6 3 2 smallest is 2: 1 2 6 3 9 smallest is 3: 1 2 3 6 9 smallest is 6: 1 2 3 6 9 33

34 Swapping The processing of the selection sort algorithm includes the swapping of two values Swapping requires three assignment statements and a temporary storage location: temp = first; first = second; second = temp; 34

35 Selection Sort public static void selectionSort (Comparable[] list) { int min; Comparable temp; for (int index = 0; index < list.length-1; index++) { min = index; for (int scan = index+1; scan < list.length; scan++) if (list[scan].compareTo(list[min]) < 0) min = scan; // Swap the values temp = list[min]; list[min] = list[index]; list[index] = temp; } 35

36 Insertion Sort consider the first item to be a sorted sublist (of one item) insert the second item into the sorted sublist, shifting the first item as needed to make room to insert the new addition insert the third item into the sorted sublist (of two items), shifting items as necessary repeat until all values are inserted into their proper positions An example: original: 3 9 6 1 2 insert 9: 3 9 6 1 2 insert 6: 3 6 9 1 2 insert 1: 1 3 6 9 2 insert 2: 1 2 3 6 9 36

37 Insertion sort algorithm public static void insertionSort (Comparable[] list) { for (int index = 1; index < list.length; index++) { Comparable key = list[index]; int position = index; // Shift larger values to the right while (position>0&&key.compareTo(list[position-1])<0) { list[position] = list[position-1]; position--; } list[position] = key; } 37

38 Comparing Sorts The Selection and Insertion sort algorithms are similar in efficiency They both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list Approximately n 2 number of comparisons are made to sort a list of size n Therefore, these sorts are of order n 2 Other sorts are more efficient: order n log 2 n 38

39 Two-Dimensional Arrays A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions 39

40 Two-Dimensional Arrays In Java a two-dimensional array is an array of arrays A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; An array element is referenced using two index values: value = scores[3][6] The array stored in one row can be specified using one index 40 ExpressionTypeDescription tableint[][] 2D array of integers, or array of integer arrays table[5]int[] array of integers table[5][12]int integer

41 Two-Dimensional Arrays 7-41 public class TwoDArray { // Creates a 2D array of integers, fills it with // increasing integer values, then prints them out. public static void main (String[] args){ int[][] table = new int[5][10]; // Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table for (int row=0; row < table.length; row++){ for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); }

42 Multidimensional Arrays An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each dimension has its own length constant Because each dimension is an array of array references, the arrays within one dimension can be of different lengths these are sometimes called ragged arrays 42


Download ppt "Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage."

Similar presentations


Ads by Google