06slide_2007 - Chapter 6 Arrays EE3206/EE5805 Java Programming& Application EE3206/EE5805 1 Objectives To describe why an array is necessary in

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 6 Arrays EE3206/EE5805 Java Programming & Application EE3206/EE5805 1 Objectives To describe why an array is necessary in programming. To To learn the steps involved in using arrays: declaring array To reference variables and creating arrays. To initialize the values in an array. To To simplify programming using JDK 1.5 enhanced for loop. To To copy contents from one array to another. To To develop and invoke methods with array arguments and To return type. To search elements using the linear or binary search algorithm. To To sort an array using the selection sort algorithm. To To declare and create multidimensional arrays. To EE3206/EE5805 Java Programming & Application EE3206/EE5805 2 Introducing Arrays Array is a data structure that represents a collection of the same types of data. double myList = new double[10]; myList reference myList[0] myList[1] Array reference variable myList[2] myList[3] myList[4] Array element at index 5 myList[5] myList[6] myList[7] myList[8] myList[9] 5.6 4.5 3.3 13.2 4 34.33 34 45.45 99.993 11123 3 Element value EE3206/EE5805 Java Programming & Application EE3206/EE5805 Declaring & Creating Array Variables To declare an array To datatype arrayRefVar; Example: double myList; double This style is allowed, but not preferred This datatype arrayRefVar; Example: double myList; Example: double To create an array To arrayRefVar = new datatype[arraySize]; Example: myList = new double[10]; myList To declare & create in one step To datatype arrayRefVar = new datatype[arraySize]; Example: double myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array. EE3206/EE5805 Java Programming & Application EE3206/EE5805 4 Array On Creation An array’s size is fixed once created An • arrayRefVar.length value on creation value • • • 0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types. Array’s elements accessed through index Array • • array indices are 0-based indexed variable format: arrayRefVar[index]; arrayRefVar[index • myList[2] = myList[0] + myList[1]; EE3206/EE5805 Java Programming & Application EE3206/EE5805 5 Initializing Array Using Shorthand The shorthand notation must be in one statement. double myList = {1.9, 2.9, 3.4, 3.5}; // correct double myList; myList = {1.9, 2.9, 3.4, 3.5}; // only declare // wrong The above shorthand notation is equivalent to the following statements: double myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5; EE3206/EE5805 Java Programming & Application EE3206/EE5805 6 Enhanced for Loop Since JDK 1.5, a new for loop is introduced to enable you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } The value in the for loop is a copy of the array element The You still have to use an index variable if you wish to change the You elements in the array or traverse the array in a different order. EE3206/EE5805 Java Programming & Application EE3206/EE5805 7 Example: Testing Arrays Objective: The program receives 6 numbers from Objective: the user, finds the largest number and counts the occurrence of the largest number entered. Suppose you entered 3, 5, 2, 5, 5, and 5, the Suppose largest number is 5 and its occurrence count is 4. TestArray Run EE3206/EE5805 Java Programming & Application EE3206/EE5805 8 Example: Assigning Grades Objective: read student scores (int), get the best score, Objective: and then assign grades based on the following scheme: • Grade is A if score is >= best–10; • Grade is B if score is >= best–20; • Grade is C if score is >= best–30; • Grade is D if score is >= best–40; • Grade is F otherwise. AssignGrade Run EE3206/EE5805 Java Programming & Application EE3206/EE5805 9 Copying Arrays 1 Often, you need to duplicate an array or a part of an array. If you Often, attempt to use the assignment statement (=), as follows: list2 = list1; Before the assignment list2 = list1; list1 After the assignment list2 = list1; list1 Contents of list1 Contents of list1 list2 list2 Contents of list2 Garbage Contents of list2 Now list2 references to the contents of list1. Now This is not a real copy. This EE3206/EE5805 Java Programming & Application EE3206/EE5805 10 Copying Arrays 2 Using a loop: Using int sourceArray = {2, 3, 1, 5, 10}; int targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i]; Using arraycopy Utility from System Class: Using arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length); EE3206/EE5805 Java Programming & Application EE3206/EE5805 11 Passing Arrays to Methods We have a method: public static void printArray(int array) { public for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } You may invoke the method like: int list = {3, 1, 2, 6, 4, 2}; printArray(list); Or invoke the method using Anonymous array: printArray(new int{3, 1, 2, 6, 4, 2}); It creates an array using the following syntax: new dataType{literal0, literal1, ..., literalk} new There is no explicit reference variable for the array. Such array is called an anonymous array. anonymous EE3206/EE5805 Java Programming & Application EE3206/EE5805 12 Pass By Value Java ALWAYS pass parameters by value. Java For a parameter of a primitive type value: For primitive • The actual value is passed. • Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. For a parameter of an array type: For array • The value of the parameter is a reference to an array. This reference is passed to the method. i.e. a copy of the reference is passed by value i.e. passed • Any changes to the array that occur inside the method body will affect the original array that was passed as the argument. EE3206/EE5805 Java Programming & Application EE3206/EE5805 13 Simple Example of Passing Parameters public class Test { public static void main(String args) { int x = 1; // x represents an int value int y = new int[10]; // y represents an array of int values m(x, y); // Invoke m with arguments x and y System.out.println("x is " + x); System.out.println("y[0] is " + y[0]); } public static void m(int number, int numbers) { number = 1001; // Assign a new value to number numbers[0] = 5555; // Assign a new value to numbers[0] } } EE3206/EE5805 Java Programming & Application EE3206/EE5805 14 Call Stack & Heap Stack Space required for method m int numbers:reference int number: 1 Space required for the main method int y: reference int x: 1 Heap The arrays are stored in a heap. Array of ten int values is stored here When invoking m(x, y), the values of x and y are passed to number and numbers. Since y contains the reference value to the array, numbers now contains the same reference value to the same array. The JVM stores the array in an area of memory, called heap, which heap is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order. EE3206/EE5805 Java Programming & Application EE3206/EE5805 15 Example: Passing Arrays as Arguments Objective: Demonstrate differences of passing primitive data Objective: type variables and array variables. Stack Space required for the swap method n2: 2 n1: 1 Space required for the main method int a reference Heap Stack Space required for the swapFirstTwoInArray method int array reference Space required for the main method int a reference a[1]: 2 a[0]: 1 Invoke swap(int n1, int n2). The primitive type values in a[0] and a[1] are passed to the swap method. The arrays are stored in a heap. Invoke swapFirstTwoInArray(int array). The reference value in a is passed to the swapFirstTwoInArray method. TestPassAray Run EE3206/EE5805 Java Programming & Application EE3206/EE5805 16 Returning an Array from a Method public static int reverse(int list) { int result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; } list result int list1 = new int{1, 2, 3, 4, 5, 6}; int list2 = reverse(list1); Similarly, a copy of the reference to result is returned to list2 Similarly EE3206/EE5805 Java Programming & Application EE3206/EE5805 17 Searching Arrays There are two commonly used approaches: There Linear Search (exhaustive search) Linear • Compares the key element, key, sequentially with each element in sequentially the array list. • Return index of the matched element. Otherwise return -1 Binary Search Binary • The elements in the array must already be ordered (ascending) ordered (ascending) • First compares the key with the element in the middle of the array • If the key is less than the middle element, you only need to search the key in the first half of the array. • If the key is equal to the middle element, the search ends with a match. • If the key is greater than the middle element, you only need to search the key in the second half of the array. • Return index of the matched element. Otherwise, returns (–insertion point – 1). The insertion point is the point at which the key would be inserted into the list. EE3206/EE5805 Java Programming & Application EE3206/EE5805 18 Example: Binary Search (found) key is 11 key < 50 list low mid high [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 2 low 4 7 10 11 45 mid high 50 59 60 66 69 70 79 key > 7 [0] [1] [2] [3] [4] [5] list 2 4 7 10 11 45 low mid high [3] [4] [5] key == 11 list 10 11 45 EE3206/EE5805 Java Programming & Application EE3206/EE5805 19 Example: Binary Search (not found) key is 54 key > 50 list low mid high [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 2 4 7 10 11 45 50 59 60 66 69 70 79 low mid high key < 66 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] list 59 60 66 69 70 79 low mid high [7] [8] key < 59 list low 59 60 high [6] [7] [8] 59 60 EE3206/EE5805 Java Programming & Application EE3206/EE5805 20 Linear Search Solution /** The method for finding a key in the list */ public static int linearSearch(int list, int key) { for (int i = 0; i < list.length; i++) if (key == list[i]) return i; return -1; } Trace the method: int int i int j int k list = {1, 4, 4, 2, 5, -3, 6, 2}; = linearSearch(list, 4); // returns 1 = linearSearch(list, -4); // returns -1 = linearSearch(list, -3); // returns 5 EE3206/EE5805 Java Programming & Application EE3206/EE5805 21 Binary Search Soluton /** Use binary search to find the key in the list */ public static int binarySearch(int list, int key) { int low = 0; int high = list.length - 1; while (high >= low) { int mid = (low + high) / 2; if (key < list[mid]) high = mid - 1; else if (key == list[mid]) return mid; else low = mid + 1; } return -1 - low; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 22 The Arrays.binarySearch Method Java provides several overloaded binarySearch methods for searching a key in an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code searches the keys in an array of numbers and an array of characters. int list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; System.out.println("Index is " + java.util.Arrays.binarySearch(list, 11)); Return is 4 char chars = {'a', 'c', 'g', 'x', 'y', 'z'}; System.out.println("Index is " + java.util.Arrays.binarySearch(chars, 't')); Return is –4 (insertion point is 3, so return is -3-1) The array must be pre-sorted in increasing order, otherwise the results The are undefined. If the array contains multiple elements with the specified value, there If is no guarantee which one will be found. The return value will be >= 0 if and only if the key is found The EE3206/EE5805 Java Programming & Application EE3206/EE5805 23 Sorting Arrays Sorting, like searching, is also a common task in computer Sorting, programming. Many different algorithms have been developed for sorting. Many This section introduces the simplest and intuitive one: selection selection sort. Selection sort Selection • finds the largest number in the list and places it last, • then finds the largest number remaining and places it next to last • and so on until the list contains only a single number. • You will learn more sorting algorithm in another course Data Data Structure and Algorithms EE3206/EE5805 Java Programming & Application EE3206/EE5805 24 animation Selection Sort int myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted 2954816 2654819 2654189 2154689 2145689 2145689 1245689 EE3206/EE5805 Java Programming & Application EE3206/EE5805 25 swap 2 Select 9 (the largest) and swap it with 6 (the last) in the list 2 Select 8 (the largest) and swap it with 1 (the last) in the remaining list 2 Select 6 (the largest) and swap it with 1 (the last) in the remaining list 2 Select 5 (the largest) and swap it with 4 (the last) in the remaining list 2 4 is the largest and last in the list. No swap is necessary 1 4 5 6 8 9 The number 5 now is in the correct position and thus no longer need to be considered. 1 6 6 5 4 9 5 4 8 1 6 swap 8 1 9 The number 9 now is in the correct position and thus no longer need to be considered. swap 5 4 1 8 9 The number 8 now is in the correct position and thus no longer need to be considered. swap 5 4 6 8 9 The number 6 now is in the correct position and thus no longer need to be considered. Selection Sort Selection swap 2 1 4 5 6 8 9 The number 4 now is in the correct position and thus no longer need to be considered. Select 2 (the largest) and swap it with 1 (the last) in the remaining list 1 2 4 5 6 8 9 The number 2 now is in the correct position and thus no longer need to be considered. Since there is only EE3206/EE5805 one number in EE3206/EE5805 Java Programming & Application the remaining list, sort is completed 26 Selection Sort Solution /** The method for sorting the numbers */ public static void selectionSort(double list) { for (int i = list.length - 1; i >= 1; i--) { // Find the maximum in the list[0..i] double currentMax = list[0]; int currentMaxIndex = 0; for (int j = 1; j <= i; j++) { if (currentMax < list[j]) { currentMax = list[j]; currentMaxIndex = j; } } // Swap list[i] with list[currentMaxIndex] if necessary; if (currentMaxIndex != i) { list[currentMaxIndex] = list[i]; list[i] = currentMax; } } } EE3206/EE5805 Java Programming & Application EE3206/EE5805 27 The Arrays.sort Method Since sorting is frequently used in programming, Java provides several overloaded sort methods for sorting an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code sorts an array of numbers and an array of characters. double numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5}; java.util.Arrays.sort(numbers); char chars = {'a', 'A', '4', 'F', 'D', 'P'}; java.util.Arrays.sort(chars); EE3206/EE5805 Java Programming & Application EE3206/EE5805 28 Two-dimensional Arrays // Declare array ref var dataType refVar; // Create array and assign its reference to variable refVar = new dataType[10][10]; // Combine declaration and creation in one statement dataType refVar = new dataType[10][10]; // Alternative syntax dataType refVar = new dataType[10][10]; EE3206/EE5805 Java Programming & Application EE3206/EE5805 29 Declaring, Creating, and Initializing Using Shorthand Notations You can also use an array initializer to declare, create and You initialize a two-dimensional array. For example, int array = { int {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; Same as int array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; EE3206/EE5805 Java Programming & Application EE3206/EE5805 30 Two-dimensional Array Illustration 01 0 1 2 3 4 matrix = new int[5][5]; 2 3 4 0 1 2 3 4 01 2 3 4 0 1 0 1 4 1 2 5 2 3 6 9 12 7 2 3 7 10 8 11 matrix[2][1] = 7; int array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; matrix.length? 5 matrix[0].length? 5 EE3206/EE5805 Java Programming & Application EE3206/EE5805 array.length? 4 array[0].length? 3 31 Lengths of Two-dimensional Arrays int x = new int[3][4]; int x x[0] x[1] x[2] x[2][0] x[2][1] x[2][2] x[2][3] x.length is 3 x[2].length is 4 x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4 x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4 int array = { array.length {1, 2, 3}, array[0].length {4, 5, 6}, array[1].length {7, 8, 9}, array[2].length {10, 11, 12} array[3].length }; array[4].length ArrayIndexOutOfBoundsException EE3206/EE5805 Java Programming & Application EE3206/EE5805 32 Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows Each can have different lengths. Such an array is known as a ragged ragged array. For example, matrix.length is 5 matrix[0].length is 5 int matrix = { matrix[1].length is 4 {1, 2, 3, 4, 5}, matrix[2].length is 3 {2, 3, 4, 5}, matrix[3].length is 2 {3, 4, 5}, matrix[4].length is 1 {4, 5}, {5} 1234 5 int triangleArray = { }; {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; 1234 123 12 12 EE3206/EE5805 Java Programming & Application EE3206/EE5805 33 Multidimensional Arrays Occasionally, you will need to represent n-dimensional data structures. In Java, you can create n-dimensional arrays for any integer n. The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare ndimensional array variables and create n-dimensional arrays for n >= 3. For example, the following syntax declares a threedimensional array variable scores, creates an array, and assigns its reference to scores. double scores = new double[10][5][2]; EE3206/EE5805 Java Programming & Application EE3206/EE5805 34 ...
View Full Document

This note was uploaded on 01/11/2011 for the course EE 3206 taught by Professor Cwting during the Spring '07 term at City University of Hong Kong.

Ask a homework question - tutors are online