Chapter 8 Fall 2006 CS 101 Aaron Bloomfield Arrays Chapter 8 Fall 2006 CS 101 Aaron Bloomfield
Introduction to arrays
Background Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional Java provides arrays and the collection classes The Vector class is an example of a collection class Consider arrays first
Example Definitions char[] c; int[] value = new int[10]; Causes Array object variable c is un-initialized Array object variable value references a new ten element list of integers Each of the integers is default initialized to 0 c can only reference char arrays v can only reference int arrays value - c …
An array example int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); Suppose 3 is extracted 8 is displayed int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = stdin.nextInt(); // element k of v given next // extracted value
Array variable definition styles Without initialization ElementType [ ] id; Type of values in list Brackets indicate array variable being defined Name of list int [] a; int a[];
Array variable definition styles With initialization Nonnegative integer expression specifying the number of elements in the array ElementType [ ] id = new ElementType [n]; A new array of n elements
Where we’ve seen arrays public static void main (String[] args) Thus, the main() method takes in a String array as the parameter Note that you can also define it as: public static void main (String args[]) or public static void main (String[] foobar)
Basic terminology List is composed of elements Elements in a list have a common name Example: a[3] = 5; The common name is ‘a’ The list as a whole is referenced through the common name List elements are of the same type — the base type Elements of a list are referenced by subscripting (indexing) the common name
Java array features Subscripts are denoted as expressions within brackets: [ ] Base (element) type can be any type Size of array can be specified at run time This is different that pure C! (for the most part, at least) Index type is integer and the index range must be 0 ... n-1 Where n is the number of elements Just like Strings indexing! Automatic bounds checking Ensures any reference to an array element is valid Data field length specifies the number of elements in the list Array is an object Has features common to all other objects More on this later… More robust than arrays in most programming languages
New 2005 demotivatiors!
Consider Segment int[] b = new int[100]; b[-1] = 0; b[100] = 0; Causes Array variable to reference a new list of 100 integers Each element is initialized to 0 Two exceptions to be thrown -1 is not a valid index – too small 100 is not a valid index – too large IndexOutOfBoundsException int[] b = new int[100]; // b has 100 elements: b[0], … b[99] b[-1] = 0; // illegal: subscript too small b[100] = 0; // illegal: subscript too large
Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex; Point[] p = new Point[3]; p[0] = new Point(0, 0); p[1] = new Point(1, 1); p[2] = new Point(2, 2); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex; Point: (1, 0) p p[0] p[1] Point: (2, 2) p[2] vertex Point: (4, 4) Point: (1, 0) p p[0] p[1] p[2] vertex Point: (4, 4) Point: (1, 0) p p[0] p[1] Point: (1, 2) Point: (2, 2) p[2] vertex Point: (4, 4) Point: (1, 0) p p[0] p[1] Point: (1, 1) Point: (2, 2) p[2] Point: (1, 0) p p[0] p[1] Point: (1, 2) Point: (2, 2) p[2] p p[0] p[1] p[2] null Point: (0, 0) p p[0] p[1] Point: (1, 1) Point: (2, 2) p[2]
Explicit initialization Syntax id references an array of n elements. id[0] has value exp0, id[1] has value exp1, and so on. ElementType id exp , exp , ... exp [] = { } ; 1 n -1 Each expi is an expression that evaluates to type ElementType
Explicit initialization Example String[] puppy = { “pika”, “mila”, “arlo”, “nikki” }; int[] unit = { 1 }; Equivalent to String[] puppy = new String[4]; puppy[0] = “pika"; puppy[1] = “mila"; puppy[2] = “arlo"; puppy[3] = “nikki"; int[] unit = new int[1]; unit[0] = 1;
Array members Member length Size of the array for (int i = 0; i < puppy.length; ++i) { System.out.println(puppy[i]); } Note that length is a field, not a method! I.e., it is not puppy.length()
Array members Member clone() Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new Point(4, 30); Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new Point(4, 30); Point: (0, 0) v v[0] v[1] Point: (1, 1) u u[0] u[1] Point: (4, 30) Point: (0, 0) v v[0] v[1] Point: (1, 1) u u[0] u[1] Point: (0, 0) Point: (1, 1) u u[0] u[1]
Array members Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1].setX(10); Member clone() Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1].setX(10); Point: (0, 0) v v[0] v[1] Point: (1, 1) u u[0] u[1] Point: (0, 0) v v[0] v[1] Point: (10, 1) u u[0] u[1] Point: (0, 0) Point: (1, 1) u u[0] u[1]
Making a deep copy We want to copy the array and all the objects each element of the array references This is called a deep copy Example Point[] w = new Point[u.length]; for (int i = 0; i < u.length; ++i) { w[i] = (Point) u[i].clone(); }
Making a deep copy
Review of arrays Creating an array: int[] foo = new int[10]; Accessing an array: foo[3] = 7; System.out.print (foo[1]); String[] bar = new String[10]; bar[3] = “qux”; System.out.println (bar[1]);
How Java represents arrays Consider int[] a = { 1, 2, 3, 4, 5 }; + … Array - length = 5 - data = 1 2 3 4 5 1 2 3 4 5 a
More about how Java represents Arrays int[] a; int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d = c; Consider int[] a; int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d = c; a c can only reference char arrays v can only reference int arrays - b null c 1 2 3 4 5 d
How are we doing with arrays? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s an array again? I’d rather not answer this question, thanks.
ArrayTools
ArrayTools.java We want to create a series of general utility methods to be used for arrays We will put these into an ArrayTools class
ArrayTools.java – outline public class ArrayTools { // class constant private static final int MAX_LIST_SIZE = 1000; // sequentialSearch(): examine unsorted list for key public static int sequentialSearch(int[] data, int key) { ... // putList (): prints list to screen public static void putList(int[] data) { ... // getList(): extract and return up to MAX_LIST_SIZE values public static int[] getList() { ... // reverse(): reverses the order of the element values public static void reverse(int[] list) { ... // binarySearch(): examine sorted list for a key public static int binarySearch(char[] data, char key) { ... }
ArrayTools.java method putList() To print the array: public static void putList(int[] data) { for (int i = 0; i < data.length; ++i) { System.out.println(data[i]); } Consider int[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 }; putList(score); Method sequentialSearch() has two formal parameters—the first parameter is an int[] array data and the second parameter is the search value key. Method sequentialSearch() is similar in form to the code segment that searched an array for a key value in Section . However, sequentialSearch() does not display a message indicating whether it found the value. If sequentialSearch() finds the key value in the array, it returns the subscript of the first matching element. If the key value is not among the array element values, sequentialSearch() returns the number of elements in the array. Because the array elements occupy subscript positions 0 through data.length-1 in the array, the value -1 indicates that the key value is not in the array.
ArrayTools.java method getList() public static int[] getList() { Scanner stdin = new Scanner (System.in); int[] buffer = new int[MAX_LIST_SIZE]; int listSize = 0; for (int i = 0; (i < MAX_LIST_SIZE) && stdin.hasNext(); ++i) { buffer[i] = stdin.nextInt(); ++listSize; } int[] data = new int[listSize]; for (int i = 0; i < listSize; ++i) { data[i] = buffer[i]; return data;
ArrayTools.java method reverse() public static void reverse(int[] data) { int[] clone = data.clone(); for ( int i = 0; i < clone.length; ++i ) { data[i] = clone[clone.length-1-i]; } Consider int[] foo = { 1, 2, 3, 4, 5 }; reverse (foo); putList (foo); Method sequentialSearch() has two formal parameters—the first parameter is an int[] array data and the second parameter is the search value key. Method sequentialSearch() is similar in form to the code segment that searched an array for a key value in Section . However, sequentialSearch() does not display a message indicating whether it found the value. If sequentialSearch() finds the key value in the array, it returns the subscript of the first matching element. If the key value is not among the array element values, sequentialSearch() returns the number of elements in the array. Because the array elements occupy subscript positions 0 through data.length-1 in the array, the value -1 indicates that the key value is not in the array.
ArrayDemo.java public class ArrayDemo { // main(): application entry point public static void main(String[] args) { System.out.println (""); System.out.println ("Enter list of integers:"); int[] numbers = ArrayTools.getList (); System.out.println ("Your list"); ArrayTools.putList (numbers); ArrayTools.reverse (numbers); System.out.println ("Your list in reverse"); System.out.println (); }
ArrayTools demo… ArrayDemo.java
How are we doing with ArrayTools? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s an array again? I’d rather not answer this question, thanks.
Today’s demotivators
… main (String args[])
Consider that main() method again public static void main (String args[]) How does one pass in a parameter to the main method? public class MainParameters { public static void main (String args[]) { System.out.println ("Number of paramters to “ + "main(): " + args.length); if ( args.length > 0 ) { for ( int i = 0; i < args.length; i++ ) System.out.println ("parameter " + i + ": '" + args[i] + "'"); }
Program Demo MainParameters.java Via JCreator Via the command line
Basic array searching
Searching for a value i = 0 System.out.println("Enter search value (number): "); int key = stdin.nextInt(); int i; if (key == data[i]) { break; if (i != data.length) { System.out.println(key + " is the " + i + "-th element"); } ++i System.out.println("Enter search value (number): "); int key = stdin.nextInt(); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + i + "-th element"); else { System.out.println(key + " is not in the list"); i < data.length
Searching for the minimum value Segment int minimumSoFar = sample[0]; for (int i = 1; i < sample.length; ++i) { if (sample[i] < minimumSoFar) { minimumSoFar = sample[i]; } The key value search code segment is typical of array processing. There is initialization to prepare for the processing of the array, a loop to process each array element in turn, and a check to see how the list processing completed. For example, the next code segment finds the minimum value of a list sample where the list size of sample is at least 1. int minimumSoFar = sample[0]; for (int i = 1; i < sample.length; ++i) { if (sample[i] < minimumSoFar) { minimumSoFar = sample[i]; } To find the minimum value in an array requires examining each element in turn. If the code segment keeps track of the minimum array element value seen so far, the lesser of that value and the current element is the minimum value seen so far. If this processing is done for each array element, then after the last array element has been considered, the minimum value seen so far is in fact the minimum. Observe that our code segment for finding the minimum of an arbitrarily sized list is even smaller than the code segment presented at the start of this chapter for finding the minimum of five values!
ArrayTools.java method sequentialSearch() public static int sequentialSearch(int[] data, int key) { for (int i = 0; i < data.length; ++i) { if (data[i] == key) { return i; } return -1; Consider int[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 }; int i1 = sequentialSearch(score, 11); int i2 = sequentialSearch(score, 30); Method sequentialSearch() has two formal parameters—the first parameter is an int[] array data and the second parameter is the search value key. Method sequentialSearch() is similar in form to the code segment that searched an array for a key value in Section . However, sequentialSearch() does not display a message indicating whether it found the value. If sequentialSearch() finds the key value in the array, it returns the subscript of the first matching element. If the key value is not among the array element values, sequentialSearch() returns the number of elements in the array. Because the array elements occupy subscript positions 0 through data.length-1 in the array, the value -1 indicates that the key value is not in the array.
How are we doing with searching? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s a search again? I’d rather not answer this question, thanks.
A solution to commenting your code The commentator: http://www.cenqua.com/commentator/
Sorting
Sorting Problem Arranging elements so that they are ordered according to some desired scheme Standard is non-decreasing order Why don't we say increasing order? Major tasks Comparisons of elements Updates or element movement Chapter introduced the notion of sorting in SortTwo.java and SortThree.java, which respectively displayed two and three input values in nondecreasing order. We used the term nondecreasing rather than increasing to allow for duplicate values. Here we consider the general sorting problem of arranging the values in a list of arbitrary size into nondecreasing order. A sort is often an iterative process such that each iteration rearranges some of the values in the list v to be sorted. For example, on iteration i the method known as selectionSort() finds the element containing the ith smallest value of its list v and exchanges that element with v[i]. As another example, on iteration i the method known as insertionSort() correctly places the value of v[i] with respect to the values stored in elements v[0] through v[i-1].
Selection sorting Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 0 Swaps smallest element with v[0] This results in smallest element being in the correct place for a sorted result v 'Q' 'E' 'W' 'Y' 'R' 'T' 'I' 'U' 'P' 'O' 2 1 5 3 4 7 6 9 8 v ‘E' ‘Q' 'W' 'Y' 'R' 'T' 'I' 'U' 'P' 'O' 2 1 5 3 4 7 6 9 8 v ‘E' ‘Q' 'W' 'Y' 'R' 'T' 'I' 'U' 'P' 'O' 2 1 5 3 4 7 6 9 8
Selection sorting Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 1 Swaps second smallest element with v[1] This results in second smallest element being in the correct place for a sorted result v 'Q' 'E' 'I' 'Y' 'R' 'T' 'W' 'U' 'P' 'O' 2 1 5 3 4 7 6 9 8 v 'Q' 'E' 'W' 'Y' 'R' 'T' 'I' 'U' 'P' 'O' 2 1 5 3 4 7 6 9 8
Selection sorting Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 2 Swaps third smallest element with v[2] This results in third smallest element being in the correct place for a sorted result v ‘O' 'E' 'I' 'Y' 'R' 'T' 'W' 'U' 'P' ‘Q' 2 1 5 3 4 7 6 9 8 v 'Q' 'E' 'I' 'Y' 'R' 'T' 'W' 'U' 'P' 'O' 2 1 5 3 4 7 6 9 8
Selection sorting Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 3 Swaps fourth smallest element with v[3] This results in fourth smallest element being in the correct place for a sorted result v ‘O' 'E' 'I' 'Y' ‘P' 'T' 'W' 'U' ‘R' ‘Q' 2 1 5 3 4 7 6 9 8 v ‘O' 'E' 'I' 'Y' 'R' 'T' 'W' 'U' 'P' ‘Q' 2 1 5 3 4 7 6 9 8
Selection sorting Algorithm basis On iteration i, a selection sorting method: Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 4 Swaps fifth smallest element with v[4] This results in fifth smallest element being in the correct place for a sorted result v ‘O' 'E' 'I' 'Y' ‘P' ‘Q' 'W' 'U' ‘R' ‘T' 2 1 5 3 4 7 6 9 8 v ‘O' 'E' 'I' 'Y' ‘P' 'T' 'W' 'U' ‘R' ‘Q' 2 1 5 3 4 7 6 9 8
ArrayTools.java selection sorting public static void selectionSort(int[] v) { for (int i = 0; i < v.length-1; ++i) { // find the location of the ith smallest element int spot = i; for (int j = i+1; j < v.length; ++j) { if (v[j] < v[spot]) { // is current location ok? // update spot to index of smaller element spot = j; } // spot is now correct, so swap elements int rmbr = v[i]; v[i] = v[spot]; v[spot] = rmbr; In analyzing a sorting algorithm, software developers are concerned normally with the total number of element comparisons and the total number of element copies/assignments performed by the sort. When i is 0 for selectionSort(), there are n – 1 element comparisons and 3 element copies/assignments, where n is the number of elements in array v. When i is 1, there are n – 2 element comparisons and 3 element copies/assignments. When i is 2, there are n – 3 element comparisons and 3 element copies/assignments. In general, on iteration i, there are n – (i + 1) element comparisons and 3 element copies/ assignments. The total number of element comparisons is therefore n – 1 + n – 2 + … + 2 + 1, which is proportional to n2. The total number of element copies/assignments is at most 3 + 3 + … + 3, which is proportional to n. Because the number of element comparisons is proportional to the square of the number of elements, we say that method selectionSort() has quadratic performance with respect to element comparisons. Because the number of element copies/assignments is proportional to the number of elements, we say that the algorithm has linear performance with respect to element copies/assignments. Because n2 > n, we say that overall algorithm performs a quadratic number of element operations.
Iteration i // find the location of the ith smallest element int spot = i; for (int j = i+1; j < v.length; ++j) { if (v[j] < v[spot]) // is spot ok? // update spot with index of smaller element spot = j; } // spot is now correct, swap elements v[spot] and v[i] The code is similar to our other array processing code. In particular, the code is most similar to the code that searches an array. The code segment begins defining int index variable guess. Variable guess represents where we believe the ith smallest element can be found. The definition initializes guess to i. The code segment then determines whether the value of guess is correct. The for loop body repeatedly tests whether v[j] < v[guess], with j iteratively taking on the values i + 1 through v.length - 1. If it is determined that v[j] < v[guess], then our value for guess is wrong and it is updated with the value of j. At this point, guess is the index of the smallest value among elements v[i] through v[j]. Thus, completing the for loop assures that guess is the index of the ith smallest element.
How are we doing with sorting? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s a sort again? I’d rather not answer this question, thanks.
Very unofficial demotivators
Binary search
Binary search Given a list, find a specific element in the list List MUST be sorted! Each time it iterates through, it cuts the search space in half A binary search is MUCH faster than a sequential search
Binary search use The ‘BS’ in BSDemo is for Binary Search, mind you public class BSDemo { public static void main(String[] args) { int[] numbers = { 9, 3, 1, 8, 4, 6, 10, 2 }; System.out.println ("The original list of numbers:"); ArrayTools.putList(numbers); System.out.println(); ArrayTools.selectionSort(numbers); System.out.println ("The sorted list of numbers:"); System.out.println ("Searching for 0: " + ArrayTools.binarySearch(numbers, 0)); System.out.println ("Searching for 1: " + ArrayTools.binarySearch(numbers, 1)); System.out.println ("Searching for 4: " + ArrayTools.binarySearch(numbers, 4)); System.out.println ("Searching for 5: " + ArrayTools.binarySearch(numbers, 5)); System.out.println ("Searching for 6: " + ArrayTools.binarySearch(numbers, 6)); System.out.println ("Searching for 10: " + ArrayTools.binarySearch(numbers, 10)); System.out.println ("Searching for 11: " + ArrayTools.binarySearch(numbers, 11)); }
Binary search use demo… BSDemo.java
Binary search public static int binarySearch (int[] data, int key) { int i = 0; // left endpoint of search interval int j = data.length-1; // right endpoint of search interval while ( i < j ) { int m = (i+j)/2; if ( key > data[m] ) { i = m+1; } else { j = m; } if ( key == data[i] ) { return i; return -1;
Binary search, take 1 public static int binarySearch (int[] data, int key) { int i = 0; int j = data.length-1; int i = 0; int j = data.length-1; while ( i < j ) { int m = (i+j)/2; if ( key > data[m] ) { i = m+1; } else { j = m; } while ( i < j ) { int m = (i+j)/2; if ( key > data[m] ) { i = m+1; } else { j = m; } if ( key == data[i] ) { return i; } else { return -1; } if ( key == data[i] ) { return i; } else { return -1; } key 14 returns: 6 a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 2 4 6 8 10 12 14 16 18 20 data i 6 5 m 4 6 5 7 j 6 7 9
Binary search But what if the element is not in the list?
Binary search, take 2 public static int binarySearch (int[] data, int key) { int i = 0; int j = data.length-1; int i = 0; int j = data.length-1; while ( i < j ) { int m = (i+j)/2; if ( key > data[m] ) { i = m+1; } else { j = m; } while ( i < j ) { int m = (i+j)/2; if ( key > data[m] ) { i = m+1; } else { j = m; } if ( key == data[i] ) { return i; } else { return -1; } if ( key == data[i] ) { return i; } else { return -1; } key 15 returns: -1 a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 2 4 6 8 10 12 14 16 18 20 data i 7 5 m 4 7 6 j 9 7
How are we doing with binary search? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s a search again? I’d rather not answer this question, thanks.
Binary search A somewhat alternative view of what a binary search does…
How long does a binary search take? Given a array of 64 elements 1st iteration cuts the array to 32 2nd iteration cuts the array to 16 3rd to 8 4th to 4 5th to 2 6th to 1 Given a array of 1024 elements 1st iteration cuts the array to 512 ... 10th iteration cuts the list to 1 element Thus, the binary search takes log2 n iterations! Where n is the size of the array
Binary search vs. sequential search Assume the array has n elements Sequential search takes n iterations to find the element Binary search takes log2 n iterations to find the element Consider a list of 1 million elements Binary search takes about 20 iterations Sequential search takes 1,000,000 iterations Consider a list of 1 trillion elements Binary search takes about 40 iterations Sequential search takes 1,000,000,000,000 iterations
How are we doing with binary search? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s a search again? I’d rather not answer this question, thanks.
Multi-dimensional arrays
Multidimensional arrays Many problems require information be organized as a two-dimensional or multidimensional list Examples Matrices Graphical animation Economic forecast models Map representation Time studies of population change Microprocessor design In addition to defining one-dimensional arrays, it is also possible to define multidimensional arrays. There are a great many problems whose solutions can be determined through the manipulation of multidimensional arrays. The application domains include matrices, graphical animation, economic forecast models, map representation, time studies of population change, and microprocessor design to name just a few.
When an array is created, each value is initialized! Example Segment int[][] m = new int[3][]; m[0] = new int[4]; m[1] = new int[4]; m[2] = new int[4]; Produces When an array is created, each value is initialized! m[0] m[1] m[2] m[2][0] m[2][1] m[2][2] m[2][3] m[0][0] m[0][1] m[0][2] m[0][3] m[1][0] m[1][1] m[1][2] m[1][3] m m
Example Alternative int[][] m = new int[3][4]; Produces m m[0] m[1] m[2][0] m[2][1] m[2][2] m[2][3] m[0][0] m[0][1] m[0][2] m[0][3] m[1][0] m[1][1] m[1][2] m[1][3]
Multidimensional array visualization A multi-dimensional array declaration (either one): int[][] m = new int[3][4]; How we visualize it: or
Example Segment for (int c = 0; c < m.length; ++c) { for (int r = 0; r < m[c].length; ++r) { System.out.print("Enter a value: "); m[c][r] = stdin.nextInt(); }
Rows by columns or columns by rows? Consider int[][] m = new int[3][4]; Is that 3 rows by 4 columns or 3 columns by 4 rows? The answer is that it can be either As long as you are consistent with your column/row placement or
Rows by columns or columns by rows? This makes it 3 columns by 4 rows: for (int c = 0; c < m.length; ++c) for (int r = 0; r < m[c].length; ++r) { System.out.print("Enter a value: "); m[c][r] = stdin.nextInt(); } This makes it 3 rows by 4 columns: for (int r = 0; r < m.length; ++r) for (int c = 0; c < m[r].length; ++c) { m[r][c] = stdin.nextInt();
Today’s demotivators
Example Segment String[][] s = new String[4][]; s[0] = new String[2]; Produces
Multidimensional array visualization Segment String[][] s = new String[4][]; s[0] = new String[2]; s[1] = new String[2]; s[2] = new String[4]; s[3] = new String[3]; Produces Called a “ragged” array or
Explicit Initialization Segment int c[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8, 9}}; Produces
Matrices A two-dimensional array is sometimes known as a matrix because it resembles that mathematical concept A matrix a with m rows and n columns is represented mathematically in the following manner
Matrix addition cij = aij + bij Definition C = A + B cij = aij + bij cij is sum of the elements in the same row and column of A and B
Matrix addition public static double[][] add(double[][] a, double[][] b) { // determine number of rows in solution int m = a.length; // determine number of columns in solution int n = a[0].length; // create the array to hold the sum double[][] c = new double[m][n]; // compute the matrix sum row by row for (int i = 0; i < m; ++i) { // produce the current row for (int j = 0; j < n; ++j) { c[i][j] = a[i][j] + b[i][j]; } return c;
Homework J9 You will be creating a Board class The Board class contains a 2-D array In each spot will be a Ship object (from a previous HW) Lab 11 is going to be a MapPrinter class Will print out the 2-D Board via text
How are we doing with 2-D arrays? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s an array again? I’d rather not answer this question, thanks.
DeCSS: The program #include<stdlib.h> typedef unsigned int uint; char ctb[512]="33733b2663236b763e7e362b6e2e667bd393db0643034b96de9ed60b4e0e4\ 69b57175f82c787cf125a1a528fca8ac21fd999d10049094190d898d001480840913d7d35246\ d2d65743c7c34256c2c6475dd9dd5044d0d4594dc9cd4054c0c449559195180c989c11058185\ 081c888c011d797df0247074f92da9ad20f4a0a429f53135b86c383cb165e1e568bce8ec61bb\ 3f3bba6e3a3ebf6befeb6abeeaee6fb37773f2267276f723a7a322f6a2a627fb9f9b1a0e9a9e\ 1f0b8f8b0a1e8a8e0f15d1d5584cd8dc5145c1c5485cc8cc415bdfdb5a4edade5f4bcfcb4a5e\ cace4f539793120692961703878302168286071b7f7bfa2e7a7eff2bafab2afeaaae2ff"; typedef unsigned char uchar;uint tb0[11]={5,0,1,2,3,4,0,1,2,3,4};uchar* F=NULL; uint lf0,lf1,out;void ReadKey(uchar* key){int i;char hst[3]; hst[2]=0;if(F==\ NULL){F=malloc(256);for(i=0;i<256;i++){hst[0]=ctb[2*i];hst[1]=ctb[2*i+1];F[i]=\ strtol(hst,NULL,16);}}out=0;lf0=(key[1]<<9)|key[0]|0x100;lf1=(key[4]<<16)|(key\ [3]<<8)|key[2];lf1=((lf1&0xfffff8)<<1)|(lf1&0x7)|0x8;}uchar Cipher(int sw1,\ int sw2){int i,a,b,x=0,y=0;for(i=0;i<8;i++){a=((lf0>>2)^(lf0>>16))&1;b=((lf1\ >>12)^(lf1>>20)^(lf1>>21)^(lf1>>24))&1;lf0=(lf0<<1)|a;lf1=(lf1<<1)|b;x=(x>>1)\ |(a<<7);y=(y>>1)|(b<<7);}x^=sw1;y^=sw2;return out=(out>>8)+x+y;} void \ CSSdescramble(uchar *sec,uchar *key){uint i;uchar *end=sec+0x800;uchar KEY[5]; for(i=0;i<5;i++)KEY[i]=key[i]^sec[0x54+i];ReadKey(KEY);sec+=0x80;while(sec!=\ end)*sec++=F[*sec]^Cipher(255,0);}void CSStitlekey1(uchar *key,uchar *im) {uchar k[5];int i; ReadKey(im);for(i=0;i<5;i++)k[i]=Cipher(0,0);for(i=9;i>=0;\ i--)key[tb0[i+1]]=k[tb0[i+1]]^F[key[tb0[i+1]]]^key[tb0[i]];}void CSStitlekey2\ (uchar *key,uchar *im){uchar k[5];int i;ReadKey(im);for(i=0;i<5;i++)k[i]=\ Cipher(0,255);for(i=9;i>=0;i--)key[tb0[i+1]]=k[tb0[i+1]]^F[key[tb0[i+1]]]^key\ [tb0[i]];}void CSSdecrypttitlekey(uchar *tkey,uchar *dkey){int i;uchar im1[6]; uchar im2[6]={0x51,0x67,0x67,0xc5,0xe0,0x00};for(i=0;i<6;i++)im1[i]=dkey[i]; CSStitlekey1(im1,im2);CSStitlekey2(tkey,im1);}
DeCSS: The shirt (and tie!)
DeCSS: The poem How to decrypt a DVD: in haiku form. (Thanks, Prof. D. S. T.) ------------------------ (I abandon my exclusive rights to make or perform copies of this work, U. S. Code Title Seventeen, section One Hundred and Six.) Muse! When we learned to count, little did we know all the things we could do some day by shuffling those numbers: Pythagoras said "All is number" long before he saw computers and their effects, or what they could do Table Zero is: Five, zero, one, two, three, four, oh, one, two, three, four. Table One is long: two to the eighth power bytes. Ready? Here they are: Fifty one; then one hundred fifteen; fifty nine; thirty eight; ninety nine; thirty five; one hundred seven; one hundred eighteen; sixty two; one hundred twenty six; fifty four; forty three; one hundred ten; then
DeCSS: The number The world’s first illegal prime number: 485650789657397829309841894694286137707442087351357924019652073668698513401047237446968797439926117510973777701027447528049058831384037549709987909653955227011712157025974666993240226834596619606034851742497735846851885567457025712547499964821941846557100841190862597169479707991520048667099759235960613207259737979936188606316914473588300245336972781813914797955513399949394882899846917836100182597890103160196183503434489568705384520853804584241565482488933380474758711283395989685223254460840897111977127694120795862440547161321005006459820176961771809478113622002723448272249323259547234688002927776497906148129840428345720146348968547169082354737835661972186224969431622716663939055430241564732924855248991225739466548627140482117138124388217717602984125524464744505583462814488335631902725319590439283873764073916891257924055015620889787163375999107887084908159097548019285768451988596305323823490558092032999603234471140776019847163531161713078576084862236370283570104961259568184678596533310077017991614674472549272833486916000647585917462781212690073518309241530106302893295665843662000800476778967984382090797619859493646309380586336721469695975027968771205724996666980561453382074120315933770309949152746918356593762102220068126798273445760938020304479122774980917955938387121000588766689258448700470772552497060444652127130404321182610103591186476662963858495087448497373476861420880529443
DeCSS: The images
DeCSS: The recordings All this info from http://www-2.cs.cmu.edu/~dst/DeCSS/Gallery/ Or do a Google search for “decss gallery”
DeCSS: The movie
This is also the review for the third midterm Vector class This is also the review for the third midterm
Limitations of arrays You can’t change their size once created This can be a big problem! So we will create a new class that will operate like an array: We can store and get elements by index number It will automatically increase in size as needed And other fancy features… Let’s call the class Vector As we are basically writing the java.util.Vector class
Properties of our Vector class It needs to have an array to hold the values As our internal array will often be bigger than the number of elements in the Vector, we need a size as well More on what this means in a slide or two… Not much else…
Methods in our Vector class Insert and remove elements into the Vector Get an element from the Vector Find the length Print it out to the screen What happens when the array field is full, and we want to add an element? We will need to increase the size of the array So we need a method to do that as well
Our first take on our Vector class public class Vector { private Object array[]; private int size = 0; Vector() { array = new Object[100]; } Vector(int length) { array = new Object[length]; What does this mean? We’ll see that a bit later… But briefly, it means the array can store any object
Adding an element to our Vector public void add (Object o) { array[size++] = o; } Pretty easy! But what if the array is full? We need a way to increase the capacity of the array
Increasing the Vector’s array’s capacity private void increaseCapacity() { int oldSize = array.length; Object newArray[] = new Object[2*oldSize]; for ( int i = 0; i < oldSize; i++ ) newArray[i] = array[i]; array = newArray; } And our new add() method: public void add (Object o) { if ( size == array.length ) increaseCapacity(); array[size++] = o;
Methods can be private as well Notice that the increaseCapacity() method is called only by the add() method when necessary It’s not ever going to be called by whomever is using our Vector Thus, we will make it private That means that only other Vector methods can call it
Removing an element from a Vector public Object remove (int which) { Object ret = array[which]; for ( int i = which; i < array.length-1; i++ ) array[i] = array[i+1]; array[array.length-1] = null; size--; return ret; }
Miscellaneous other methods public int size() { return size; } public Object get (int which) { return array[which];
Today’s demotivators
Our toString() method public String toString() { String ret = "["; for ( int i = 0; i < size; i++ ) { ret += array[i]; if ( i != size-1 ) ret += ", "; } ret += "]"; return ret;
Using our Vector This code is in a separate class called VectorUsage public static void main (String[] args) { Vector v = new Vector(); for ( int i = 12; i < 30; i++ ) { v.add (String.valueOf(i)); } System.out.println (v); System.out.println (v.size()); String s = (String) v.get(5); System.out.println (s); v.remove (5);
Program Demo VectorUsage.java
The “real” Vector class Java provides a Vector class In java.util It contains all of the methods shown
Program Demo VectorUsage.java But using java.util.Vector
What about those errors? When compiled with java.util.Vector, we see: Note: C:\...\VectorUsage.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. You can ignore these They deal with generics (aka templates), which you will see in future courses The program was still compiled
More on using the Vector class To add a String object s to the end of a Vector v v.add(s); To get the String object at the end of the Vector v String s = (String) v.get(v.size()-1); To remove a String object from the end of a Vector v String s = (String) v.remove(v.size()-1); This both removes the object from the Vector and stores the removed value into s
How are we doing with Vectors? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s an array again? I’d rather not answer this question, thanks.
Wrapper classes
But what about adding variables? The add method takes an Object as a parameter public void add (Object o) { Although we haven’t seen it yet, this means you can add any object you want to the vector Primitive types (i.e. variables) are not objects How can they be added? The solution: wrapper classes!
The Integer wrapper class This is how you add an int variable to a Vector: int x = 5; Integer i = new Integer(x); vector.add (i); //… Integer j = (Integer) v.get(0); int y = j.intValue(); Pretty annoying syntax – we’ll see how to get around it in a bit…
More on wrapper classes All the primitive types have wrapper classes Usually, the names are just the capitalized version of the type I.e. Double for double, Byte for byte, etc. Two exceptions: int and char int has Integer char has Character
More on wrapper classes Consider this code: int x = 5; vector.add (x); //… int y = vector.get(0); Does this code work? It shouldn’t As we are adding a variable (not an object) to a vector But it does work! Why?
Auto-boxing Java 1.5 will automatically “wrap” a primitive value into it’s wrapper class when needed And automatically “unwrap” a wrapper object into the primitive value So Java translates the previous code into the following: int x = 5; vector.add (new Integer(x)); //… int y = ((Integer)vector.get(0)).intValue(); This is called autoboxing And auto-unboxing (unauto-boxing?) This does not work in Java 1.4 or before
More on auto-boxing Consider the following code: Double d = 7.5; Double e = 6.5; Double f = d + e; System.println (f); This is doing a lot of auto-boxing (and auto-unboxing): Double d = new Double(7.5); Double e = new Double(6.5); Double f = newDouble(d.doubleValue() + e.doubleValue());
How are we doing with Wrapper classes? Very well! This stuff is so easy. With a little review, I’ll be good. Not very well at all. I’m so lost. What’s Java again? I’d rather not answer this question, thanks.
Star Wars Episode 3 Trailer
Star Wars Episode 3 Trailer That was a edited version I changed the PG-rated trailer to a G-rated trailer The original one can be found at http://www.sequentialpictures.com/ Or Google for “star wars parody”