1 / 57

Lecture F - Arrays

Lecture F - Arrays. Unit F1 - Introduction to Arrays . Lesson or Unit Topic or Objective. Basic Introduction to Arrays . Collections. Programs usually handle large amounts of data Names of all people in the class A Matrix

lindsay
Download Presentation

Lecture F - 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. Lecture F - Arrays Unit F1 - Introduction to Arrays

  2. Lesson or Unit Topic or Objective Basic Introduction to Arrays

  3. Collections • Programs usually handle large amounts of data • Names of all people in the class • A Matrix • Your program needs to be able to store and handle collections of data items, without giving each data item a separate name. • Several ways to handle collections in your program • Arrays • Built in collection library (e.g. class Vector) • Linked Data Structures

  4. 0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91 Arrays • An array is an ordered list of values • Each value has a numeric index • An array of size N is indexed from 0 to N-1 • The following array of integers has a size of 10 and is indexed from 0 to 9

  5. 0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91 Arrays • A particular value in an array is referenced using the array name followed by the index in brackets • For example, the expression scores[4] refers to the value 67 • That expression represents a place to store a single integer, can be used wherever an integer variable can • For example, it can be assigned a value, printed, used in a calculation

  6. Arrays • An array stores multiple values of the same type • That type can be primitive types or object reference • Therefore, we can create an array of integers, or an array of characters, or an array of String references, etc. • In Java, the array itself is an object • Therefore it is accessed through a reference

  7. Declaring Arrays • The scores array could be declared as follows: • Note that the type of the array does not specify its size, but each object of that type has a specific size • The type of the variable scores is int[] (a reference to an array of integers) • It is set to refer to a newly instantiated array of 10 integers int[] scores = new int[10];

  8. Declaring Arrays • Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] text = new char[1750];

  9. Reverse public class Reverse { public static void main(String[] args){ int[] elements; InputRequestor in = new InputRequestor(): int size = in.requestInt(“Enter number of elements:”); elements = newint[size]; for ( int j=0 ; j<size ; j++ ) elements[j] = in.requestInt(“enter element “ + j); for( int j=size-1 ; j>=0 ; j-- ) System.out.println(elements[j]); } }

  10. DigitsHistogram public class DigitsHistogram { public static void main(String[] args) { InputRequestor input = new InputRequestor(); int n = input.requestInt(“Enter a number:”); int[] histogram = new int[10]; while (n>0) { int digit = (int)(n%10); histogram[digit]++; n/=10; } for (int i=0; i<10; i++) { System.out.print(i+” “); for (int j=0; j<histogram[i]; j++) System.out.print(“*”); System.out.println(); } } }

  11. DigitHistogram Output The result for the input 20901225321 will be: 0 ** 1 ** 2 **** 3 * 4 5 * 6 7 8 9 *

  12. Array length • Each array object has a public field called length that stores the size of the array • It is referenced through the array name (just like any other object): scores.length • Note that length holds the number of elements, not the largest index

  13. Using Array length in loops • We can now rewrite the printing loop of the previous program: for (int i=0; i< histogram.length; i++) { output.print(i+” “); for (int j=0; j<histogram[i]; j++) { output.print(“*”); } output.println(); }

  14. Initializer Lists • An initializer list can be used to instantiate and initialize an array in one step • The values are delimited by braces and separated by commas • Examples: int[] units = {147, 323, 89, 933, 540}; char[] vowels = {’a’,’o’,’i’,’u’,’e’};

  15. 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 only be used in the declaration of an array

  16. Arrays of Characters vs. Strings • A String Object is not an Array of characters • Strings are immutable, Array entries can be changed • Strings may be constructed from an array of characters • There is a natural correspondence • a.length vs. s.length() • a[i] vs. s.charAt(i) char[] a = newchar[20]; // … put something into a String s= new String(a)

  17. FindVowels public class FindVowels { public static void main(String[] args){ char[] vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}; InputRequestor in = new InputRequestor(); String s = in.requestString(“Enter a word:”); for (int j = 0 ; j < s.length() ; j++) for (int k =0 ; k < vowels.length ; k++) if (s.charAt(j) == vowels[k] ){ System.out.println(“Found a vowel!”); break; } } }

  18. Arrays as Parameters • A reference to an array can be passed to a method as a parameter • Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other • As the method access the array through an alias reference, the content of the array can be changed. • Of course, an array element can be passed to a method like any other value.

  19. Lecture F - Arrays Unit F2 – Arrays of Objects

  20. Arrays of Objects Using arrays of objects

  21. Arrays of Objects • The elements of an array can be object references • The declaration reserves space to store 25 references to String objects (initially all the references are null) • It does NOT create the String objects themselves • Each object stored in an array must be instantiated separately String[] words = new String[25];

  22. TurtleJungle public class TurtleJungle { static final int STEP = 5; public static void main(String[] args) { InputRequestor in = new InputRequestor(); int numberOfTurtles = in.requestInt(“Number of turtles:”); Turtle[] turtles = new Turtle[numberOfTurtles]; for (int i=0; i<turtles.length; i++) { turtles[i] = new Turtle(); turtles[i].turnLeft((int)(Math.random()*360)); turtles[i].tailUp(); } while(true) for (int i=0; i<turtles.length; i++) turtles[i].moveForward(STEP); } }

  23. Multidimensional Arrays • A one-dimensional array stores a simple list of values • A two-dimensional array can be thought of as a table of values, with rows and columns • A two-dimensional array element is referenced using two index values • A two-dimensional array in Java is an array of arrays • Two ways to construct a multidimensional array • Construct each row explicitly – each row may have a different length • Use a shorthand for square matrices

  24. Diagonal Matrix public class DiagonalMatrix { public static void main(String[] args){ int[][] mat = new int[10][]; for (int j = 0 ; j < mat.length ; j++) mat[j] = new int[j+1]; for (int j = 0 ; j < mat.length ; j++) for (int k = 0 ; k < mat[j].length ; k++) mat[j][k] = j*k; // … }

  25. MultiplicationTable public class MultiplicationTable { public static void main(String[] args){ int[][] table = new int[10][10]; for (int j = 0 ; j < table.length ; j++) for (int k = 0 ; k < table[0].length ; k++) table[j][k] = j*k; for (int j = 0 ; j < table.length ; j++){ for (int k = 0 ; k < table[j].length ; k++) System.out.print(table[j][k] + “ ”); System.out.println(); } } }

  26. Initializing Multidimensional Arrays • An initializer list can be used to create and set up a multidimensional array • Each element in the list is itself an initializer list int[][] hadamard = { { 1, 1, 1, 1}, {-1, 1, -1, 1}, {-1, -1, 1, 1}, {-1, -1, -1, 1} };

  27. Command Line arguments • When a java program is activated from the shell, the user can pass parameters to it. • java MyClass parameters • The OS shell breaks the line (after the class name) into words. • The static void main(String) method receives these words in an array of Strings.

  28. EchoTwice public class EchoTwice { public static void main(String[] args){ for(int i=0 ; i<args.length ; i++) { for(int j=0; j<2 ; j++) System.out.print(args[i]); System.out.println(); } } }

  29. Running EchoTwice

  30. Lecture F - Arrays Unit F3 - Polynomial Class Example

  31. Polynomial Example An example of an object that contains an array

  32. Arrays in Objects • Many objects hold a large amount of data in them • In many such cases the data is simply kept in a field that is an array • Usually, when the object is constructed, the array should be allocated • Here we provide an example

  33. Polynomial /** * A polynomial. A real valued function of the form * f(x)=a0+a1x+a2x^2+...+an*x^n. */ public class Polynomial { // coefficients[i] is the coefficient of x^i private double[] coefficients;

  34. Polynomial constructor /** * Constructs a polynomial from the given array of * coefficients. * @param coefficients The coefficients of * of the polynomial. */ public Polynomial(double[] coefficients) { this.coefficients = newdouble[coefficients.length]; for(int i=0 ; i<coefficients.length ; i++) this.coefficients[i]=coefficients[i]; }

  35. valueAt /** * Computes the value of this polynomial at a * given point. * @return The value of this polynomial at x. */ public double valueAt(double x) { double value = 0.0; double power = 1.0; for (int i=0; i<coefficients.length; i++) { value += coefficients[i]*power; power *= x; } return value; }

  36. getDegree /** * Returns the degree of the polynomial. * @return The degree of the polynomial. */ public int getDegree() { int degree = coefficients.length-1; while (coefficients[degree]==0.0) { degree--; } return degree; }

  37. plus /** * Computes the polynomial resulting from the addition * of this polynomial and p. The sum is returned, but * the value of this polynomial is not changed */ public Polynomial plus(Polynomial p) { int degree = Math.max(getDegree(), p.getDegree()); double[] sum = new double[degree]; for (int i=0; i<degree; i++) sum[i] = coefficients[i] + p.coefficients[i]; return new Polynomial(coefficients); }

  38. getCoefficients /** * Returns the coefficients of the polynomial. */ public double[] getCoefficients() { double[] copy = new double[coefficients.length]; System.arraycopy(coefficients, 0, copy, 0, coefficients.length); return coefficients; } }// class set

  39. PolynomialUseExample // Prints a table of values for x^3-2x^2+5x+7 class PolynomialUseExample { static final double LOWER_LIMIT = -5.0; static final double UPPER_LIMIT = 5.0; static final double STEP = 1.0; public static void main(String[] args) { double[] coefficients = {7.0, 5.0, -2.0, 1.0}; Polynomial p = new Polynomial(coefficients); System.out.println(“x \t y”); for (double x=LOWER_LIMIT; x<=UPPER_LIMIT; x+=STEP) { double y = p.valueAt(x); System.out.println(x+” \t “+y); } } }

  40. Lecture F - Arrays Unit F4 - Sorting and Searching

  41. Sorting & Searching How and why to sort And how to search a sorted array

  42. The Sorting problem • One of the most common computational tasks • Input: an array of numbers • Output: the numbers in the array re-ordered so they would be in increasing order • Example: {4, 1, 6, 1, 3}  {1, 1, 3, 4, 6} • May be applied to an array of any type with total order • Strings: “hello” < “hi” < “there” • Fractions: ¼ < 1/3 < ½ < 2/3 • Our examples will sort integers; easy to change to other types. • Later in the course we will learn how to write a “generic” sorter that applies to all appropriate types

  43. Sorting Algorithms • Simple Sorting Algorithms • Selection sort • Insertion sort • Bubble sort • Efficient Sorting algorithms • Merge sort • Quick sort • Heap sort • Sorting Algorithms for small domains • Out of memory sorting • Parallel sorting • Distributed sorting

  44. Selection Sort publicclass SelectionSort{ public static void main(String[] args) { int[] test = {8, 4, 6, 9, 3,2,2}; selectionSort(test); for (int j = 0 ; j < test.length ; j++) System.out.println(test[j]); } public static void selectionSort (int[] a) { for (int j = 0 ; j < a.length-1 ; j++) { // find index of minimal element in a[j]…a[length] int min = j; for (int k = j+1 ; k < a.length ; k++ ) if (a[k] < a[min]) min = k; // switch minimal element to j’th place if (min != j) { int temp = a[min] ; a[min] = a[j] ; a[j] = temp; } } } }

  45. Sample run for (int j = 0 ; j < a.length-1 ; j++) { int min = j; for (int k = j+1 ; k < a.length ; k++ ) if (a[k] < a[min]) min = k; if (min != j) { int temp = a[min] ; a[min] = a[j] ; a[j] = temp; } } The algorithm for {8,4,6,9,3,5,2} will be: jmina[] 0 6 2,4,6,9,3,5,8 1 4 2,3,6,9,4,5,8 2 4 2,3,4,9,6,5,8 3 5 2,3,4,5,6,9,8 4 6 2,3,4,5,6,8,9

  46. Running Time Analysis • If N is the input length then the outer loop runs N-1 iterations, j=0 … N-1 • In iteration j the inner loop runs for N-j-1 iterations • Each inner loop takes O(1) time • Total time is O-of: for (int j = 0 ; j < a.length-1 ; j++) { min = j; for (int k = j+1 ; k < a.length ; k++ ) if (a[k] < a[min]) min = k; if (min != j) { int temp = a[min] ; a[min] = a[j] ; a[j] = temp; } }

  47. Merge Sort public static void mergeSort (int[] a) { sort(a,0,a.length-1); } private static void sort(int a[], int low, int high) { if (low >= high ) return; int med = (low + high)/2; sort(a, low, med); sort(a, med+1, high); merge(a, low, med, high); } privatestaticvoid merge(int[] a, int low, int med, int high) { int[] temp = newint [high-low + 1]; int i = 0 , j = low , k = med + 1; while (i < temp.length) { if (k > high || (j<= med && a[j] < a[k])) temp[i++] = a[j++]; else temp[i++] = a[k++]; } for (int i = 0; i < temp.length ; i++) a[low + i] = temp[i]; }

  48. Sample Run if (low >= high ) return; int med = (low + high)/2; sort(a, low, med); sort(a, med+1, high); merge(a, low, med, high); The algorithm for {23,14,21,9} will be: Recursion Levellowhighmed level: 0 0 3 1 level: 1 0 1 0 level: 2 0 0 level: 2 1 1 level: 1 2 3 2 level: 2 2 2 level: 2 3 3

  49. Sample Run sort(a,0,3); sort(a,0,1); sort(a,2,3); sort(a,0,0); sort(a,3,3); sort(a,1,1); sort(a,2,2); merge(a,0,0,1); merge(a,2,2,3); merge(a,0,1,3);

  50. Running Time Analysis • merge(a, low, med, high) runs in O(m) time, where m=high-low is the size of the input to merge(). • The running of sort(a, low, high) is thus given by the recursion T(m)=2T(m/2)+O(m), where m=high-low is the size of the input to sort() • The solution of this recursion is T(n)=O(n log n) private static void sort(int a[], int low, int high){ if (low >= high ) return; int med = (low + high)/2; sort(a, low, med); sort(a, med+1, high); merge(a, low, med, high); }

More Related