Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays Includes Some Review

Similar presentations


Presentation on theme: "Arrays Includes Some Review"— Presentation transcript:

1 Arrays Includes Some Review
CIS265/506 Arrays Includes Some Review CIS265/506: Chapter 02

2 Introduction Imagine we have a problem that requires us to process 20 integers. We could put every number in a different variable: Number_0 Number_1 Number_2 Number_19 CIS265/506: Chapter 02

3 Introduction In Java it will simply be something like:
int number1, number2, number3, number4, number5, number6, number7, number8, number9, number10, number11, number12, number13, number14, number15, number16, number17, number18, number19, number20; Easy, but that looks like it could be troublesome to manage. Well, maybe not for 20 integers, but what about 20,000? CIS265/506: Chapter 02

4 Introduction What if we make one variable that can hold all our integers? Then we only have one name to remember… that might make it easier. For this, we use a powerful structure called an array. CIS265/506: Chapter 02

5 What is an Array? An array is a fixed size, sequenced collection of elements of the same data type CIS265/506: Chapter 02

6 What is an Array? Elements scores scores[0] scores[1] scores[2]
Indexes scores[0] scores[1] scores[2] scores[3] scores[4] scores[5] scores[6] scores[7] scores[8] 23 45 12 67 95 56 34 83 Elements Name of the array scores CIS265/506: Chapter 02

7 Sept 3, 1998 Arrays An array’s name is a symbolic reference for the address to the first byte of the array. The index represents an offset from the beginning of the array being referred to. elementAddress = arrayAddress + (sizeof(element) * index) Let us say that this spot is address location “A21” Imagine this is an array of integers. If we want the address of element 4, we would say: Address of E[4] = A21 + (2 * 4) = A = A29 CIS265/506: Chapter 02 CIS265/506: Chapter 02 28

8 What is an Array? An array must be declared and defined before it is used Declaration & definition tell the compiler the name of the array, the type of each element, and the size or number of elements in the array The size is constant and must have a value at compile time These are called “Static Arrays” CIS265/506: Chapter 02

9 A small difference Java supports Dynamic Arrays
The size can be given at compile or run time Use the new operator Arrays are objects in Java CIS265/506: Chapter 02

10 How do we declare an array?
We can declare and define in two steps or one. Two steps One step int[ ] scores; scores = new int[9]; int[ ] scores = new int[9]; CIS265/506: Chapter 02

11 Declaring Arrays char [] vowels; // Declare a character array variable
vowels = new char[5]; // Define an array of 5 characters The declaration statement declares the array name. It does not allocate any space in memory The definition statement will create enough space in memory to store a character array of length 5. The vowels will have every element initialized to ‘\u0000’ (Unicode null character). CIS265/506: Chapter 02

12 Initial Values Java arrays are initialized to a default value
A good practice is to initialize them to your own value(s) All numeric arrays are initialized to zero All boolean arrays are initialized to false All character arrays are initialized to ‘\u0000’ All class-type arrays are initialized to null CIS265/506: Chapter 02

13 Storing Values in the array
We can store (or place) values in our array in two different ways Initialize the array Input values during execution of the program CIS265/506: Chapter 02

14 Initializing the Array
Method One: When the array is declared Method two: One element at a time int[ ] scores = { 23, 45, 12, 67, 95, 45, 56, 34, 83}; scores[0] = 23; scores[1] = 45; scores[2] = 12; CIS265/506: Chapter 02

15 Initializing the Array
Method three: Using Loops Initializing the array using a loop is useful if the array values are sequential or dependant on some function (i.e. a random set of numbers) int[ ] scores = new int[9]; for (int z = 0; z < 9; z++) { scores[z] = z; } CIS265/506: Chapter 02

16 Array Length Once you have created the array, you can use the length attribute (a data member of the array object). Why? Knowing the length will prevent you from going past the ‘end’ of the array – trying to access elements that are not there CIS265/506: Chapter 02

17 Initializing the Array with Array Length
We use length, a data member of the array object: int[] scores = new int[9]; for (int z = 0; z < scores.length; z++) { scores[z] = z; } CIS265/506: Chapter 02

18 Array Length double[] samples = new double[50];
for (int L1 = 0; L1 < 50; L1 ++) { samples[L1] = * Math.random(); // random values } double average = 0.0; for (int L2 = 0; L2 < samples.length; L2++) { average += samples[L2]; average /= samples.length; CIS265/506: Chapter 02

19 How do we look at each element?
Java uses an index to access the individual elements The index is usually some numeric constant, and is always an integer i i -1 i + 1 CIS265/506: Chapter 02

20 Accessing Array elements
Refer to an element of an array by the array name followed by the element’s index in square brackets Remember that the array starts with index zero! vowels[0] vowels[1] vowels[2] vowels[3] vowels[4] 1 2 3 4 CIS265/506: Chapter 02

21 Accessing Array elements
What happens if you attempt access an array element that does not exist? For instance vowels[10] ? Java will throw an EXCEPTION – or generate an error. This exception is called IndexOutOfBounds CIS265/506: Chapter 02

22 Working with the array public class scores {
public static void main(String[] args) { int[ ] scores = { 23, 45, 12, 67, 95, 45, 56, 34, 83}; int sum = 0; for (int i = 0; i < scores.length; i++) { sum += scores[i]; } System.out.println("The sum of the scores is: " + sum); CIS265/506: Chapter 02

23 Sept 3, 1998 Arrays To copy one array to another, you must copy each element individually: for (j = 0; j < 25; j++) { second[j] = first[j]; } CIS265/506: Chapter 02 CIS265/506: Chapter 02 31

24 Arrays of Objects Now that we have made arrays of primitive data types, you can start to think to yourself that we should be able to make arrays of anything You're right Well… there may be some things we can't make arrays from, but at least for today, there are probably no limits CIS265/506: Chapter 02

25 Book class public class Book { // class variables
private String title; private int pages; // constructor public Book(String title, int pages) { this.title = title; this.pages = pages; } // mutators public Book() { this.title = ""; this.pages = 0; public int getPages() { return pages; public void setPages(int p) { pages = p; public String getTitle() { return title; public void setTitle(String t) { title = t; public void showBook() { //user defined method to show data Book class

26 public class Book_Driver { public static void main(String[] args) {
// reserve memory space for 4 Book objects Book[] theBooks = new Book[4]; CIS265/506: Chapter 02

27 // Actually create each book
theBooks[0] = new Book(); // Call the constructor theBooks[0].setPages(450); theBooks[0].setTitle("The Shining"); theBooks[1] = new Book(); theBooks[1].setPages(900); theBooks[1].setTitle("Java By Example"); theBooks[2] = new Book(); theBooks[2].setPages(225); theBooks[2].setTitle("100 Years of Solitude"); theBooks[3] = new Book(); theBooks[3].setPages(51); theBooks[3].setTitle("The McGuffey Reader"); CIS265/506: Chapter 02

28 /*******Show results *******/ for (int i = 0; i < 4; i++) {
System.out.println("Book " + (i+1) + " is " + theBooks[i].getTitle() + " with " + theBooks[i].getPages() + " pages." ); } Book 1 is The Shining with 450 pages. Book 2 is Java By Example with 900 pages. Book 3 is 100 Years of Solitude with 225 pages. Book 4 is The McGuffey Reader with 51 pages. CIS265/506: Chapter 02

29 Searching Arrays To search through an array, we combine a "for" loop and (usually) an "if" statement We look at each element in the array (iteration), and ask if that element meets our criteria (condition testing) If so we do something, if not we (usually) skip it CIS265/506: Chapter 02

30 for (int i = 0; i < prices.length; i++ ) { sum += prices[i];
public class priceChecker { public static void main(String[] args) { // declare & initialize the array double[] prices = {2.34, 3.11, ,9.32, 4.00, 7.11, 5.01, 6.43, 2.11, 0.32, 21.21, 32.11, 11.65, 1.12, 0.88, 1.13, 5.12, 6.99, 7.99, 1.88}; // declare and initialize sum, average double sum = 0.0; double average = 0.0; // Column Heading for the first thing we need to print System.out.println("The values less than 5.00 are: "); // loop thru the array for (int i = 0; i < prices.length; i++ ) { sum += prices[i]; if (prices[i] < 5.00) { System.out.println("\t" + prices[i]); } … Code continues… CIS265/506: Chapter 02

31 Arrays & Methods How do you pass an array to a function?
Sept 3, 1998 Arrays & Methods How do you pass an array to a function? Individual elements are passed to a function like any ordinary variable. To pass the entire array - in the calling function, use the array name as the actual parameter. In the called function, you need to say that the corresponding formal parameter type is an array. CIS265/506: Chapter 02 CIS265/506: Chapter 02 33

32 Passing Arrays to Methods
When we pass an entire array to a method, we pass the address of the array This means our method not only has access to every element in the array, but can change each element as well CIS265/506: Chapter 02

33 changeArray(myArray);
public class passingArrays { public static void changeArray(int[] newArray) { System.out.println("In Method \n\n\nOld Value\tNew Value"); for (int i=0; i < newArray.length; i++) { System.out.print(newArray[i] + "\t\t"); newArray[i] += 3; System.out.println(newArray[i]); } System.out.println("\n\nReturning from method\n\n"); public static void main(String[] args) { int[] myArray = {1, 2, 3, 4, 5}; System.out.println("In Main \n\n\nValue"); for (int i=0; i < myArray.length; i++) { System.out.println(myArray[i]); System.out.println("\n\nGoing to method\n\n"); changeArray(myArray); System.out.println("In Main After Method\n\n\nValue");

34 In Main Value 1 2 3 4 5 Going to method In Method Old Value New Value 1 4 2 5 3 6 4 7 5 8 Returning from method In Main After Method 6 7 8

35 Arrays of Arrays Just as we had arrays with one index, we can have arrays with multiple indices. We call these multi-dimensional arrays CIS265/506: Chapter 02

36 An array of arrays 1 2 3 4 0 1 2 3 4 First dimension (rows)
1 2 3 4 Second dimension (columns) CIS265/506: Chapter 02

37 An array of arrays (row-wise)
table[0][0] table[0][1] table[0][2] table[0][3] table[0] table[1][0] table[1][1] table[1][2] table[1][3] table[1] table[2][0] table[2][1] table[2][2] table[2][3] table[2] table CIS265/506: Chapter 02

38 Working with two-dimensional arrays
// declare & initialize the array int[ ][ ] table = { { 0, 1, 2, 3}, {10, 11, 12, 13}, {20, 21, 22, 23} }; // printing the array for (int i = 0; i < table.length; i++) { for (int j=0; j < table[i].length; j++) { System.out.println( " i = " + i + " , j = " + j + " and the array value is " + table[i][j]); } CIS265/506: Chapter 02

39 Data Structures Searching CIS265/506: Chapter 02 1

40 Introduction Consider the problem of looking up a word to see if it is spelled correctly. How would we do this? CIS265/506: Chapter 02 CIS265/506: Chapter 02 2

41 Introduction We could start out by making a list of all the words known to us. This could be a huge list… right? How would we manage the list? CIS265/506: Chapter 02 CIS265/506: Chapter 02 3

42 Introduction First, the obvious things: Now, the not-so-obvious:
Maintenance: Inserting, deleting, updating Now, the not-so-obvious: How do we EFFICIENTLY find anything in a list so large? CIS265/506: Chapter 02 CIS265/506: Chapter 02 4

43 What we know... We could store this in a list
How do we find things in a list? CIS265/506: Chapter 02 CIS265/506: Chapter 02 6

44 A few terms... a table or file contains groups of elements
each group is called a record COBOL File: xxxxxx yyyyyyy zzzz aa qq  a record xxxxxx yyyyyyy zzzz bb qq  a record xxxxxx yyyyyyy zzzz cc qq  a record xxxxxx yyyyyyy zzzz dd qq  a record CIS265/506: Chapter 02 CIS265/506: Chapter 02 7

45 A few terms... Each record has a key keys can be simple or complex
If the key is part of the record, it is internal or embedded If there is a separate list of keys (for example, a table of items that point to the records), these are called external keys CIS265/506: Chapter 02 CIS265/506: Chapter 02 8

46 Keys: Examples Your address book collection: <Last name, First name> What if each person has a home phone, business phone, fax, cell phone, …… ? Maybe we need to assign each a number to each person, and another id for the type of phone. Person PhoneType Person PhoneType 1 H 2 H 1 W 2 W 1 C 2 C 1 F 2 F That might work…. CIS265/506: Chapter 02 CIS265/506: Chapter 02 9

47 Keys: Examples Would these be internal or external keys? It depends.
1 H 1 W 1 C 1 F Bill Smith Bill Smith Bill Smith Bill Smith these are ……._______________? CIS265/506: Chapter 02 CIS265/506: Chapter 02 10

48 Keys: Examples 1 H Bill Smith W Bill Smith C Bill Smith F Bill Smith these are ……._______________? CIS265/506: Chapter 02 CIS265/506: Chapter 02 11

49 Keys Why did we go to so much trouble to make sure our key pointed to only a single record? What is wrong with using just last name? What if Bill Smith has a son, who is also Bill Smith? And Junior also has four phone numbers? Wow. How do we keep track? CIS265/506: Chapter 02 CIS265/506: Chapter 02 12

50 Keys We call the key or set of keys that makes each record unique the primary key. Generally speaking, a primary key is always unique. CIS265/506: Chapter 02 CIS265/506: Chapter 02 13

51 Keys We can also have a key that is used to sort items
Example: Suppose you want to sort your phone list by state, so you can plan a trip to visit everyone. “State” is not unique - many people live in one state. We call this key a secondary key - it does not have to be unique. CIS265/506: Chapter 02 CIS265/506: Chapter 02 14

52 Now what? We now have a pretty good idea how our data elements are organized. We can now start to think of a search algorithm that will be optimized for our data. CIS265/506: Chapter 02 CIS265/506: Chapter 02 15

53 A few more terms… A search algorithm is a methodology to find a requested value. (Note we never mention how - that is still a ways away.) The algorithm can return an entire record, a pointer to the record, or nothing (The requested item was not found, so NULL was returned). CIS265/506: Chapter 02 CIS265/506: Chapter 02 16

54 A few more terms… An algorithm that inserts a new record whenever the search value indicates it was not found, is called a placement or search & insertion algorithm A search process is called a retrieval. A table of records in which a key is used for retrieval is called a search table, index or dictionary CIS265/506: Chapter 02 CIS265/506: Chapter 02 17

55 A few more terms… Searches in which the entire table is constantly kept in main memory are called internal searches Searches which use auxiliary storage (disks, tapes,…) are called external searches CIS265/506: Chapter 02 CIS265/506: Chapter 02 18

56 Performance Predication and the “Big O” Notation.
One way of deciding what algorithm is “better” is to figure out how the running time of the algorithm will vary or grow as a function of the “problem size”. Problem size takes into account things like the number of elements in the array, the number of records in the file and so forth. Your algorithm may work well & quickly for a small file, but may take an extraordinarily long time when running on a large data set. CIS265/506: Chapter 02 CIS265/506: Chapter 02 2

57 Performance Predication and the “Big O” Notation.
An example: What if you have a program that takes 1 second on a block holding10 records, 4 seconds on 2 blocks (each holding 10 records), 100 seconds on 10 blocks (each holding10 records). CIS265/506: Chapter 02 CIS265/506: Chapter 02 3

58 Performance Predication and the “Big O” Notation.
An example: continuation Observe the relationships are: 1sec:1b lock, 4sec:2bloks, 100sec:10block The running time of this program varies with the square value of the sample size time ≈ numberBlocks2 Therefore 1000 records (fitting in 100 blocks) will predictably take 10,000 seconds (about 3 hours!) and 10,000 records (1000 blocks) will take two weeks!! CIS265/506: Chapter 02 CIS265/506: Chapter 02 3

59 Performance Predication and the “Big O” Notation.
We will look at a few ways to determine growth rate of algorithms. This growth rate is often called the “Big O (‘oh’) Notation” - where the ‘O’ is “order of magnitude”. For the previous example we write the order formula O(2 n) Where n represents the number of blocks in the file. CIS265/506: Chapter 02

60 Performance Predication and the “Big O” Notation.
How do we try & predict the growth rate? We try and write a formula for the computational time in terms of the program size n. This formula takes into account programming language, compiler, and computer. The formula allows for a estimate of complexity that can be used for comparison of growth rate from one problem to another. CIS265/506: Chapter 02 CIS265/506: Chapter 02 4

61 Performance Predication and the “Big O” Notation.
The common growth rates you will encounter include: (from highest to lowest) O(n!) - factorial growth rate O(n3) - cubic growth rate O(n2) - quadratic: proportional to the square of N O(n * log(n)) - usually written as O(nlogn) O(n) - linear growth rate O(log(n)) - logarithmic growth rate O(K) - constant growth rate CIS265/506: Chapter 02 CIS265/506: Chapter 02 5

62 Performance Predication and the “Big O” Notation.
O(n) - linear O(logn) - logarithmic O(K) - constant O(nlogn) - logarithmic O(n2) - quadratic O(n3) CIS265/506: Chapter 02 CIS265/506: Chapter 02 6

63 Performance Predication and the “Big O” Notation.
OBSERVATION Fast algorithms have lower orders (constant, linear, …) Slow algorithms have higher orders (exponential, factorial…) CIS265/506: Chapter 02 CIS265/506: Chapter 02 6

64 Performance Predication and the “Big O” Notation.
How do we estimate the growth rate of an algorithm? If you have a simple statement - like an assignment statement, or some other statement without any function calls - the growth rate of this statement is O(K) or constant. The growth rate of a (nested) counting loop is some function of N - either constant, O(N), O(N2), O(N3), etc. The growth rate of a multiplicatively-controlled loop is some function of logN - either O(logN), O(NlogN), etc. CIS265/506: Chapter 02 CIS265/506: Chapter 02 7

65 Performance Predication and the “Big O” Notation.
A counting loop is something like: for (i=1; i< 10; i++) { some activity; } A multiplicatively-controlled loop is something like: for (i=1; i< 100; i=i*2) { some activity; } CIS265/506: Chapter 02 CIS265/506: Chapter 02 8

66 Performance Predication and the “Big O” Notation.
We’ll leave the proofs & further discussion of this topic for the algorithm class. However, you will need some understanding of this to see why one searching/sorting algorithm is more efficient than another. CIS265/506: Chapter 02 CIS265/506: Chapter 02 9

67 Sequential Searching A sequential search starts at the beginning of an array, and goes from one cell to the next until the item is found, or the end of the array is reached. A sample code fragment: for (i = 0; i < n; i++) if (searchItem == array[i]) return i; return (-1); //Not found! CIS265/506: Chapter 02 CIS265/506: Chapter 02 2

68 Sequential Searching searchItem1 = 21 searchItem2 = 22 17 19 21 23 25
1 2 3 4 5 6 7 8 9 10 11 12 13 15 17 19 21 23 25 27 29 31 searchItem1 = 21 searchItem2 = 22 CIS265/506: Chapter 02 CIS265/506: Chapter 02 3

69 Sequential Searching If we search an array for a record, and do not find it, what next? Exit Routine Report message to user Add the Element Must insure no two records have the same key Can not go past the upper bound of the array CIS265/506: Chapter 02 CIS265/506: Chapter 02 4

70 Sequential Searching We can eliminate some of these problems by changing the supporting data structure to a linked list, rather than an array. Why linked lists will be better? No worries about upper bounds checking Can insert in-order and uniqueness checks will not be as difficult. Deleting an element from a list is very simple. The efficiency of a sequential search is O(n) CIS265/506: Chapter 02 CIS265/506: Chapter 02 6

71 Important Points It is (obviously?) more efficient to search an ordered group of elements vs. an unordered group It is “easier” to work with lists vs. arrays The data structures and actual search techniques are application specific CIS265/506: Chapter 02 CIS265/506: Chapter 02 7

72 Indexed Sequential Search
The indexed sequential search can speed searching in a sorted file An auxiliary table, called an index, is built. The index is held in addition to the sorted file We find where our item would fall in the index & search only that section of the sorted file. CIS265/506: Chapter 02 CIS265/506: Chapter 02 8

73 Indexed Sequential Search
Imagine a phone book: Your friend’s last name starts with “S”. Rather than start at the beginning of the phone book, and search the entire book for your friend’s number, you start at the section beginning with “S”. CIS265/506: Chapter 02 CIS265/506: Chapter 02 9

74 Indexed Sequential Search
key Record Able Amos Baker Blue Charlie Delta Dumas Echo . . . key index pointer index A B C D E . . . CIS265/506: Chapter 02 CIS265/506: Chapter 02 10

75 Indexed Sequential Search
The algorithm: Search the index table until you find the place where the record might be located. Follow the pointer pointerIndex to reach the correct record location on the main sorted file. Search the area between the pointerIndex where you started and the next pointerIndex. Record found: return the key Record not found: Either insert record, or return message to user. CIS265/506: Chapter 02 CIS265/506: Chapter 02 11

76 Indexed Sequential Search
Things to watch out for: If there are multiple records with the same key, your search may not always return the first one! Application specific If the index table is very large, a secondary index table can be built Insert & delete not as trivial as they may seem CIS265/506: Chapter 02 CIS265/506: Chapter 02 12

77 Binary Search Very efficient Does not involve auxiliary tables.
Can be used with auxiliary tables, not not necessary. Can be either recursive or non-recursive Most algorithms require this search to be used on an array. CIS265/506: Chapter 02 CIS265/506: Chapter 02 13

78 Binary Trees 1 1 = 2 - 1 2 3 = 4 - 1 4 7 = 8 - 1 8 15 = 16 - 1 2n
Level Nodes at this level Total nodes in the tree 1 1 = 2 - 1 2 3 = 4 - 1 4 7 = 8 - 1 3 8 15 = n 2n 2n+1 – 1 Binary Trees Level 0 0.1 Level 1 1.1 Level 2 2.1 2.2 1.2 2.3 2.4 A search is done by traversing the tree from one level to the next. A data set of size n that is arranged as a balanced binary tree has log2(n) levels. CIS265/506: Chapter 02 CIS265/506: Chapter 02 13

79 Binary Search Insertions & Deletions
Not trivial to insert or delete items from arrays and still maintain order. Several algorithms exist for this purpose The efficiency of a binary search is O(logn) CIS265/506: Chapter 02 CIS265/506: Chapter 02 14

80 Binary Search Assume you have a sorted list. You are looking for an item in the list. 1. Choose the center of the list. 2. Is your item greater than, equal to or less than the center point? 2a. Greater - Repeat items 1 & 2 with the upper half of the list 2b. Equal - Exit routine, returning the index of the array 2c. Less - Repeat items 1 & 2 with the lower half of the list 3. If not found, exit with message to user CIS265/506: Chapter 02 CIS265/506: Chapter 02 15


Download ppt "Arrays Includes Some Review"

Similar presentations


Ads by Google