dr. sahar shabanah lecture 3: arrays. data structures data structures are organized collections of...

42
CPCS204: Data Structure 1 Dr. Sahar Shabanah Lecture 3: Arrays

Upload: neal-arnold

Post on 14-Dec-2015

224 views

Category:

Documents


1 download

TRANSCRIPT

  • Slide 1

Dr. Sahar Shabanah Lecture 3: Arrays Slide 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 Slide 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 doesnt 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 Slide 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 Slide 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 Slide 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 Slide 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 Slide 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 Slide 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 Slide 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 Slide 11 Bounds Checking Its 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; index0 && 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 thats larger than newScore //entry[i] has been copied to the right, so all we need to do is replace it entry[i] = e; } 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 thats 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 thats larger than newScore //entry[i] has been copied to the right, so all we need to do is replace it entry[i] = e; } 30 Slide 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 Slide 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 Slide 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 Slide 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 Slide 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 Slide 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 Slide 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])