Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays.

Similar presentations


Presentation on theme: "Arrays."— Presentation transcript:

1 Arrays

2 Programming: The Big Picture
Three fundamental ideas to understand and use effectively: flow of control iteration/conditionals modular design subroutines/recursion data representation data types/data structures

3 Data Structures A data structure is a way of storing data in a computer so that it can be used efficiently typically data that is more complex than just a number or a truth value The choice of data structure used to store data can impact the performance of your program

4 Data Structures Given a collection of data:
1, 1, 5, 3, 1, 5, 4, 1, 1 How do we want to store this? [4*1, 0*2, 1*3, 1*4, 2*5] (bag) {1,3,4,5} (set) [1,1,5,3,1,5,4,1,1] (list) Depends on the application e.g. voting vs. scheduling

5 Data Structures Given a collection of data: Do we expect more data?
1, 1, 5, 3, 1, 5, 4, 1, 1 Do we expect more data? more data arriving at the tail? more data arriving in the middle? All of these factors together should be considered in choosing a data representation

6 Each value has a numeric index
Arrays An array is an ordered list of values scores The entire array has a single name Each value has a numeric index An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

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

8 Arrays For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]);

9 Arrays Limitations: so…
Array length is fixed when the array is created Can only hold a single type so… Can’t lengthen an array mid-program Can’t store an int and a String in the same array

10 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 arrays of integers, arrays of Strings, arrays of BankAccounts In Java, the array itself is an object that must be instantiated

11 Declaring Arrays Use the new syntax
To create a pointer to an array, append a [] to the element type String[] names; int[] scores; Like other object types, this creates a reference – not an object

12 Declaring Arrays To allocate the memory for the array: Creates this:
e.g. create an array of 10 ints: new int[10]; all at once: int[] scores = new int[10]; Creates this: scores

13 Declaring Arrays Note that the type of the variable scores is int[]
An array of integers The array type does not specify its size The type is not an “array of size 10” However, every object of type array has a specified size

14 Declaring Arrays Some other examples of array declarations:
float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

15 Manipulating Array Elements
Some sample array commands: int[] myArray = new int[100]; myArray[0] = 2; myArray[4] = myArray[0] + 1; System.out.println(myArray[4]); \\ prints 3 myArray[99] = 2; \\ ok myArray[100] = 2; \\ error

16 Bound Checking Array of size N has indices 0,…,N-1
Referencing an element with an index larger than N-1 results in an “ArrayIndexOutOfBoundsException” This is called automatic bounds checking

17 Bounds Checking It’s common to produce one-off errors:
int[] codes = new int[100]; for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; Solution: use the public length constant and the strictly less than relation

18 The length Constant Each array object has a public constant called length that holds the number of elements note: not the highest index It is referenced with the array name: e.g. codes.length So this is a safer loop: for (int index=0; index < codes.length; index++) codes[index] = index*50 + epsilon;

19 The Iterator for Loop Can also use the “iterator version” of the for loop: for (int score : scores) System.out.println (score); This is only appropriate when processing all array elements from top (lowest index) to bottom (highest index)

20 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

21 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: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

22 Initializer Lists 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

23 Arrays as Parameters An entire array can be passed as a parameter
Example: the main method takes an argument of type String[] This array is obtained from command-line arguments

24 Command Line Arguments
public class CommandLineTest { public static void main (String[] args) System.out.println(“First parameter: “ + args[0]); System.out.println(“Second parameter: + args[1]); }

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

26 Two Dimensional Arrays
Declared as follows: int[][] scores = int[12][10]; Elements referenced by pairs: value = scores[4][8]; \\two bounds to check To be accurate… this is just an array of arrays… not a new type An entire row can be referenced with a single index arrayvariable = scores[4];

27 The ArrayList Class Included in the java.util package
Essentially, it is an array that can grow and shrink add elements and remove elements Another advantage: can store multiple types

28 The ArrayList Class Example: Creates a new array list
ArrayList lunch = new ArrayList(); lunch.add(“apple”); lunch.add(“peanut butter sandwich”); System.out.println(lunch); Creates a new array list Adds two string elements Prints both out (using hidden toString() )

29 The ArrayList Class Elements can be inserted or removed with a single method invocation When an element is inserted, the other elements "move aside" to make room Likewise, when an element is removed, the list "collapses" to close the gap The indexes of the elements adjust accordingly

30 ArrayList Efficiency The ArrayList class is implemented using an underlying array The array is manipulated so that indexes remain continuous as elements are added or removed If elements are added to and removed from the end of the list, this processing is fairly efficient But as elements are inserted and removed from the front or middle of the list, the remaining elements are shifted

31 Searching

32 Searching A common problem: find an item in an array find exact match
find item that contains… return position return element

33 Linear Search In general, we need to go through every element in the array Pseudocode: for i from 0 to length – 1 if array[i]=target : return i return -1 \\ indicates target not in array Java implementation in text

34 Properties Will work on any array Problem: it is slow
searches every element will find target if it’s there Problem: it is slow might not be necessary in some arrays

35 Binary Search Suppose we have a sorted array
then we can avoid looking at every element We are looking for 17 in this array Half the array can quickly be eliminated Look in the middle: 29 Can ignore second half of the array

36 Details Keep track of the “candidate” part of the array
Look at the middle of the candidate part Found it? DONE! Not found? Throw away one half

37 Pseudocode first = 0 \\ start of candidate array
last = length -1 \\ end of candidate array while first <= last mid = (first+last)/2 if (array[mid]=target): return mid else if (array[mid] < target): first = mid+1 else if (array[mid] > target): last = mid-1 return -1 \\ not in array

38 Example, again first = 0, last =12, mid = 6
first = 0, last =5, mid = 2 first = 3, last =5, mid = 4 return 4

39 Speed binary search linear search
example took 3 steps worst case: 4 ( approx. log2(n) ) linear search worst case: 13 (=n) binary search is much faster for large arrays but we need the array to be sorted… how much work does that require…


Download ppt "Arrays."

Similar presentations


Ads by Google