420 likes | 555 Views
CPCS204: Data Structure 1. Dr. Sahar Shabanah Lecture 3: Arrays. 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:
E N D
CPCS204: Data Structure 1 Dr. Sahar Shabanah Lecture 3: Arrays
Data Structures • Data structures are organized collections of information and a set of operationsused 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
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
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 areencapsulated
The entire array has a single name Each value has a numeric index 79 87 94 82 67 98 87 81 74 91 scores 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 An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9
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]);
79 scores 87 94 82 67 98 87 81 74 91 Arrays • Another way to depict the scores array: • 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
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
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);
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]);
problem 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;
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
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};
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 a 79 b 87 94 82 67 98 87 81 74 91
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
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
- words - - - - Arrays of Objects • The words array when initially declared: • At this point, the following reference would throw a NullPointerException: • System.out.println (words[0]);
“friendship” words “loyalty” “honor” - - Arrays of Objects • After some String objects are created and stored in the array: • 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"};
Tunes CDCollection - collection : CD[] - count : int - totalCost : double + main (args : String[]) : void + addCD (title : String, artist : String, cost : double, tracks : int) : void + toString() : String - increaseSize() : void CD - title : String - artist : String - cost : double - tracks : int 1 * + toString() : String Arrays of Objects • A UML diagram for the Tunes program:
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++; }
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); • Define overloaded versions of the average method • Downside: we'd need a separate version of the method for each parameter count
Indicates a variable length parameter list element type array name Variable Length Parameter Lists • 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 }
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);}
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}
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”); }
Using Arrays Example • Storing Game entries • High Scores Class • Game entry insertion • Game entry removal
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(Stringn, ints) { name = n; score = s; } /** Retrieves the name field */ public String getName() { return name; } /** Retrieves the score field */ public intgetScore() { return score; } /** Returns a string representation of this entry */ public String toString() { return "(" + name + ", " + score + ")”;} }
High Scores Class /** Class for storing high scores in an array in non-decreasing order. */ public class Scores { public static final intmaxEntries = 10; // number of high scores we keep protected intnumEntries; // 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 (inti = 0; i < numEntries; i++) { if (i > 0) s += ", "; // separate entries by commas s += entries[i]; } return s + "]"; } ....... }
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)
Game Entry Insertion (cont.) public void insert(GameEntrye) { intnewScore = 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 inti = 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; }
Game Entry Removal • remove entryi,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 GameEntryremove (inti) throws IndexOutOfBoundsExceptio { if ((i < 0)||(i >= numEntries)) throw IndexOutOfBoundsException(“invalidindex:”+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 (intj= 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 }
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
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
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;
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; } }
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
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; } }
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 n2 number of comparisons are made to sort a list of size n • Therefore, these sorts are of order n2 • Other sorts are more efficient: order n log2n
one dimension Two-Dimensional Arrays • A one-dimensional arraystores a list of elements • A two-dimensional arraycan be thought of as a table of elements, with rows and columns two dimensions
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
Two-Dimensional Arrays 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 (intcol=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table for (int row=0; row < table.length; row++){ for (intcol=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); } } }
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