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

Slides:



Advertisements
Similar presentations
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Advertisements

Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Wecksten, Mattias Arrays Based on templates from Lewis & Loftus.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 6: Arrays Java Software Solutions Third Edition
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java Software.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
© 2004 Pearson Addison-Wesley. All rights reserved October 13, D Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor:
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.
Programming in Java (COP 2250) Lecture Chengyong Yang Fall, 2005.
1 Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 7: Arrays.
Chapter 7 Arrays: Part 1 of 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of.
© 2004 Pearson Addison-Wesley. All rights reserved October 15, 2007 Searching ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2004 Pearson Addison-Wesley. All rights reserved October 10, 2007 Parameter Lists & Command Line Arguments ComS 207: Programming I (in Java) Iowa State.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Sorting b Sorting is the process of arranging a list of items into a particular order b There must be some value on which the order is based b There.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Parameter Lists & Command Line Arguments
Arrays, 2-D Arrays, and ArrayList
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Outline Late Binding Polymorphism via Inheritance
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Arrays.
Presentation transcript:

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: 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

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

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

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 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

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

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 Another way to depict the scores array: 7

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

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

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

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

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

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

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 b

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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: smallest is 1: smallest is 2: smallest is 3: smallest is 6:

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

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

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: insert 9: insert 6: insert 1: insert 2:

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

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

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

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

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(); }

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