1 / 105

Arrays

Arrays. Chapter 8 Spring 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

moe
Télécharger la présentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays Chapter 8 Spring 2006 CS 101 Aaron Bloomfield

  2. Introduction to arrays

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

  4. c - … value 0 0 0 0 0 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

  5. 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(); 8 is displayed Suppose 3 is extracted

  6. ElementType [ ] id; Brackets Name of Type of indicate array list values in variable being list defined Array variable definition styles • Without initialization int [] a; int a[];

  7. Nonnegative integer expression specifying the number of elements in the array ElementType id ElementType [n]; = new [ ] A new array of n elements Array variable definition styles • With initialization

  8. 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)

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

  10. 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…

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

  12. vertex vertex vertex p[0] p[0] p[0] p[0] p[0] p[0] p[0] p[1] p[1] p[1] p[1] p[1] p[1] p[1] p[2] p[2] p[2] p[2] p[2] p[2] p[2] null null null p p p p p p p Point: (4, 4) Point: (4, 4) Point: (4, 4) Point: (1, 0) Point: (0, 0) Point: (1, 0) Point: (1, 0) Point: (1, 0) Point: (1, 0) Point: (1, 1) Point: (1, 2) Point: (1, 1) Point: (1, 2) Point: (2, 2) Point: (2, 2) Point: (2, 2) Point: (2, 2) Point: (2, 2) Consider 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[] 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;

  13. New 2005 demotivatiors!

  14. id references an array of n elements. id[0] has value exp0, id[1] has value exp1, and so on. Each expiis an expression that evaluates to type ElementType Explicit initialization • Syntax ElementType id exp , exp , ... exp [] = { } ; 0 1 -1 n

  15. 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;

  16. Array members • Member length • Size of the array for (int i = 0; i < puppy.length; ++i) { System.out.println(puppy[i]); }

  17. u[0] u[0] u[0] u[1] u[1] u[1] u u u Point: (0, 0) Point: (0, 0) Point: (0, 0) Point: (1, 1) Point: (1, 1) Point: (1, 1) v v Point: (4, 30) v[0] v[0] v[1] v[1] 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);

  18. u[0] u[0] u[0] u[1] u[1] u[1] u u u Point: (0, 0) Point: (0, 0) Point: (0, 0) Point: (10, 1) Point: (1, 1) Point: (1, 1) v v v[0] v[0] v[1] v[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);

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

  20. Making a deep copy

  21. Review of arrays • Creating an array: int[] foo = new int[10]; • Accessing an array: foo[3] = 7; System.out.print (foo[1]); • Creating an array: String[] bar = new String[10]; • Accessing an array: bar[3] = “qux”; System.out.println (bar[1]);

  22. Array - length = 5 - data = + … 1 2 3 4 5 1 2 3 4 5 How Java represents arrays • Consider int[] a = { 1, 2, 3, 4, 5 }; a

  23. c d b null a 1 0 2 0 3 0 4 0 5 0 More about how Java represents Arrays • Consider int[] a; int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d = c; int[] a; int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d = c; -

  24. What do these pictures mean? • Light beer • Dandy lions • Assaulted peanut • Eggplant • Dr. Pepper • Pool table • Tap dancers • Card shark • King of pop • I Pod • Gator aide • Knight mare • Hole milk

  25. ArrayTools

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

  27. 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) { ... }

  28. 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);

  29. 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; }

  30. 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);

  31. Demo.java public class Demo { // main(): application entry point publicstaticvoidmain(String[]args){ System.out.println (""); System.out.println ("Enter list of integers:"); int[] numbers = ArrayTools.getList (); System.out.println (""); System.out.println ("Your list"); ArrayTools.putList (numbers); ArrayTools.reverse (numbers); System.out.println (""); System.out.println ("Your list in reverse"); ArrayTools.putList (numbers); System.out.println (); } }

  32. ArrayTools demo… • ArrayDemo.java

  33. … main (String args[])

  34. 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] + "'"); } } }

  35. Program Demo • MainParameters.java • Via JCreator • Via the command line

  36. Basic array searching

  37. Searching for a value 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 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 = 0 i < data.length

  38. 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]; } }

  39. ArrayTools.java method sequentialSearch() publicstaticintsequentialSearch(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);

  40. Today’s demotivators

  41. Sorting

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

  43. 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 v v v ‘Q' 'E' ‘Q' 'W' 'W' 'W' 'Q' ‘E' ‘E' 'R' 'R' 'R' 'T' 'T' 'T' 'Y' 'Y' 'Y' 'U' 'U' 'U' 'I' 'I' 'I' 'O' 'O' 'O' 'P' 'P' 'P' 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

  44. 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 v v 'E' 'E' 'W' 'I' 'Q' 'Q' 'R' 'R' 'T' 'T' 'Y' 'Y' 'U' 'U' 'W' 'I' 'O' 'O' 'P' 'P' 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

  45. 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 v v 'E' 'E' 'I' 'I' 'Q' ‘O' 'R' 'R' 'T' 'T' 'Y' 'Y' 'U' 'U' 'W' 'W' ‘Q' 'O' 'P' 'P' 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

  46. 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 v v 'E' 'E' 'I' 'I' ‘O' ‘O' 'R' ‘P' 'T' 'T' 'Y' 'Y' 'U' 'U' 'W' 'W' ‘Q' ‘Q' 'P' ‘R' 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

  47. 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 v v 'E' 'E' 'I' 'I' ‘O' ‘O' ‘P' ‘P' ‘Q' 'T' 'Y' 'Y' 'U' 'U' 'W' 'W' ‘T' ‘Q' ‘R' ‘R' 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

  48. 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; } }

  49. 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; } // spotisnowcorrect,swap elementsv[spot]andv[i]

More Related