Download presentation
Presentation is loading. Please wait.
Published byCrystal Joseph Modified over 9 years ago
1
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi
2
Chapter 5 Methods Memory management Variable scope Last Week
3
Chapter 6 Arrays Declaration Initialization Access Common operations Summing all entries, max, min, … for-each loop Variable length argument list Linear search, binary search Sorting Objectives
4
Arrays
5
Read one hundred numbers, compute their average, and find out how many numbers are above the average. Declaring 100 integer variables? Motivation
6
Better solution: using arrays Array is a data structure that represents a collection of the same type of data. Solution int [] myList = new int [7]; 23 45 53 16 32 8 91
7
Array is a reference type Solution 23 45 53 16 32 8 91 int [] myList = new int [7]; 0x675 myList (memory location of the actual array) Array element at index 6 Value of element at index 6
8
First approach: Example: Second approach (possible, but not preferred): Example: Declaring Array datatype[] arrayRefVar; double[] myList; datatype arrayRefVar[]; double myList[];
9
Example: Creating Array arrayRefVar = new datatype[arraySize]; //two steps double[] myList; myList = new double[10]; //one step double[] myList= new double[10];
10
Once an array is created, its size is fixed. i.e. it cannot be changed! You can find the size of an array using For example This returns 7. Length of Array arrayRefVar.length int length = myList.length;
11
When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types '\u0000' for char false for boolean Initial Values
12
The array elements are accessed through an index. The array indices are 0-based, i.e., myList indices starts from 0 to 6. Indexed Variables
13
Each element of array is an indexed variable: Example (accessing first element) Indexed Variables arrayRefVar[index]; myList[0];
14
Individual initialization Populate Array double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
15
Shorthand initialization This shorthand syntax must be in one statement. Splitting it would cause a syntax error! Populate Array double[] myList = {1.9, 2.9, 3.4, 3.5};
16
First create an array Populate the array Use indexed variables to access items in the same way as a regular variable. Indexed Variables myList[2]= myList[0] + myList[1];
17
Read one hundred numbers, compute their average, and find out how many numbers are above the average. Program AnalyzeNumbers
18
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } Declare array variable Values
19
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } Declare array variable, and create an array. Values
20
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } i is 1 Values
21
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } i is less than 5 Values
22
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } After this line is executed, value[1] is 1 Values
23
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } i is 2 now Values
24
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } i (=2) is less than 5 Values
25
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } After this line is executed, value[2] is 3 Values
26
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } After i++, i becomes 3 Values
27
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } i (=3) is less than 5 Values
28
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } After this line, values[3] becomes 6 (3 + 3) Values
29
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } After this, i becomes 4 Values
30
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } i (=4) is still less than 5 Values
31
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } After this, values[4] becomes 10 (4 + 6) Values
32
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } After i++, i becomes 5 Values
33
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } i ( =5) < 5 is false. Exit the loop Values
34
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } After this line, values[0] is 11 (1 + 10) Values
35
Program Trace public class Test { public static void main(String[] args) { int [] values = new int [5]; for ( int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } Finished Values
36
PA3 was posted on Friday Poll on Sakai Announcement
37
Chapter 5 Methods Memory management Variable scope Chapter 6 Array Last Week
38
Initializing arrays with input values Example Scanner input = new Scanner(System.in); for ( int i = 0; i < myList.length; i++) myList[i] = input.nextDouble();
39
Initializing arrays with random values Example for ( int i = 0; i < myList.length; i++) { myList[i] = Math.random() * 100; }
40
Printing arrays Example for ( int i = 0; i < myList.length; i++) System.out.print(myList[i] + " ");
41
Summing all elements Example double total = 0; for ( int i = 0; i < myList.length; i++) total += myList[i];
42
Finding the largest element Example double max = myList[0]; for ( int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; }
43
Random shuffling Example for ( int i = 0; i < myList.length; i++) { // Generate an index randomly int index = ( int )(Math.random() * myList.length); // Swap myList[i] with myList[index] double temp = myList[i]; myList[i] = myList[index]; myList[index] = temp; }
44
Shifting Elements Example double temp = myList[0]; // Retain the first element // Shift elements left for ( int i = 1; i < myList.length; i++) { myList[i - 1] = myList[i]; } // Move the first element to fill in the last position myList[myList.length - 1] = temp; myList
45
for-each Loops
46
JDK 1.5 introduced a new for loop that enables 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-each for (double value: myList) System.out.println(value); for (elementType value:arrayRefVar) …
47
Suppose you play the Pick-10 lotto. Each ticket has 10 unique numbers ranging from 1 to 99. You buy a lot of tickets. You like to have your tickets to cover all numbers from 1 to 99. Write a program that reads the ticket numbers from a file and checks whether all numbers are covered. Assume the last number in the file is 0. Program Run Lotto Numbers Sample Data
48
The problem is to write a program that picks four cards randomly from a deck of 52 cards. All the cards can be represented using an array named deck, filled with initial values 0 to 52, as follows: Program DeckOfCards Run int[] deck = new int[52]; // Initialize cards for (int i = 0; i < deck.length; i++) deck[i] = i;
49
Cards 0-12: 13 Spades Cards 13-25: 13 Hearts Cards 26-38: 13 Diamonds Cards 39-51: 13 Clubs Suit: 0-3 (i.e. Spades, Hearts, Diamonds, Clubs) Rank: 0-12 (i.e. Ace, 2, …, 10, Jack, Queen, King) deck / 13: suit of the card (0-3) deck % 13: rank of the card (0-12) Program
51
Array Copy
52
Arrays are reference type, so be careful! After assignment, both lists will point to the same memory location. Array Copy list2 = list1;
53
To copy the contents (and not the reference), you can use a loop: Array Copy 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];
54
To copy the contents (and not the reference), you can also use the arrayCopy utility: Example Array Copy System.arraycopy(source, srcPos, target, tarPos, length); int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; System.arraycopy(sourceArray, 0, targetArray, 0,sourceArray.length);
55
Passing Array
56
Two ways to pass an array to a method Passing Array public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); } int[] list = {3, 1, 2, 6, 4, 2}; printArray(list); printArray(new int[]{3, 1, 2, 6, 4, 2}); Anonymous Array
57
Two Java uses pass by value to pass arguments to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. Passing Values 23 45 53 16 32 8 int [] y = new int [7]; y int x = 10 ; 10 x
58
For a parameter of a primitive type value: The actual value is passed. Changing the value inside the method does not affect the value outside the method. For a parameter of an array (reference) type: The value of the parameter contains a reference to an array Any changes to the array that occur inside the method body will affect the original array that was passed as the argument. Passing Values
59
Midterm exam Regular class time on Feb. 27 In the class (PUGH 170) Based on the materials in the lectures notes, textbook, homework Textbook: chapters 1, 2, 3, 4, 5, 6 Lecture notes: 1, 2, 3, 4, 5, 6 Announcements
60
Exam review session Next week: Wednesday or Friday No homework this week Poll closing on Monday, vote! Announcements
61
Objective: Demonstrate differences of passing primitive data type variables and array variables. Program TestPassArrayRun
62
Return Array 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; } int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); list 123456 result 654321
63
Generate 100 lowercase letters randomly and assign to an array of characters. Count the occurrence of each letter in the array. Program CountLettersInArrayRun
64
Variable-Length Argument Lists
65
You can pass a variable number of arguments to a method Type should be followed by an ellipsis (…) Variable Length args Typename … parameterName
66
Only one variable-length argument in each method Must be the last parameter Variable Length args
67
Java treats it like an array You can use An array or The variable-length argument list Variable Length args
68
Problem: finding the maximum in a list of unspecified number of values Variable Length args VargArgsDemoRun
69
Searching & Sorting
70
The process of looking for a specific element in a list A common task in computer programming We will learn about two commonly used approaches Linear search Binary search Search
71
Example Search public class LinearSearch { /** The method for finding a key in the list */ public static int linearSearch(int[] list, int key) { int result = -1; for (int i = 0; i < list.length; i++) if (key == list[i]) result = i; return result; }
72
The linear search approach compares the key element, sequentially with each element in the array list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1. Linear Search
73
Illustration of linear search Linear Search 64197328 64197328 64197328 64197328 64197328 64197328 3 3 3 3 3 3 Key List
74
Array Search Linear search Binary search Sort Selection sort Insertion sort Previously
75
For binary search to work, the elements in the array must already be ordered. e.g. 2 4 7 10 11 45 50 59 60 66 69 Binary Search
76
1. Compare the key with the element in the middle of the array 2. If the key is less than the middle element, you only need to search the key in the “first half” of the array. 3. If the key is equal to the middle element, the search ends with a match. 4. If the key is greater than the middle element, you only need to search the key in the “second half” of the array. Binary Search
77
Example Binary Search 12346789 12346789 12346789 8 8 8 KeyList
78
Binary Search /** 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; int result = -1; while (high >= low) { int mid = (low + high) / 2; if (key < list[mid]) high = mid - 1; else if (key == list[mid]) result = mid; else low = mid + 1; } if(result == -1) result = -1 – low; return result; }
79
Java provides several overloaded binarySearch methods (Arrays should be ordered) Binary Search int [] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 79}; int index = java.util.Arrays.binarySearch(list, 11)); char [] chars = {'a', 'c', 'g', 'x', 'y', 'z'}; int index =java.util.Arrays.binarySearch(chars, 't'));
80
More? “The Art of Computer Programming” by Donald Knuth. Search & Sort
81
We will look at two different types of sorting Selection sort Insertion sort Sorting
82
1. Find the largest (smallest) number in the list and place it last (first). 2. Then find the largest (smallest) number remaining and place it next to last (first) 3. Repeat step 2 until the list contains only a single number Selection Sort
84
Program design Selection Sort for ( int i = 0; i < list.length; i++) { //select the smallest element in list[i..list.length-1]; //swap the smallest with list[i], if necessary; }
85
//find the smallest element in the unsorted portion of the list Selection Sort double currentMin = list[i]; int currentMinIndex = i; for ( int j = i; j < list.length; j++) { if (currentMin > list[j]) { currentMin = list[j]; currentMinIndex = j; }
86
// if list[i] is in its correct position Selection Sort if (currentMinIndex != i) { list[currentMinIndex] = list[i]; list[i] = currentMin; }
87
Selection Sort /** The method for sorting the numbers */ public static void selectionSort(double[] list) { for (int i = 0; i < list.length; i++) { // Find the minimum in the list[i..list.length-1] double currentMin = list[i]; int currentMinIndex = i; for (int j = i + 1; j < list.length; j++) { if (currentMin > list[j]) { currentMin = list[j]; currentMinIndex = j; } // Swap list[i] with list[currentMinIndex] if necessary; if (currentMinIndex != i) { list[currentMinIndex] = list[i]; list[i] = currentMin; } selectionSort
88
The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted. Insertion Sort
89
int[] myList = {2, 9, 5, 4, 8, 1, 6}; Insertion Sort
90
Example: int[] myList = {2, 9, 5, 4, 8, 1, 6}; Insertion Sort 2954816 2954816 2594816 2458916 1245896 2459816 1245689 InsertSort
91
public static void insertionSort( double [] list) { for ( int i = 1; i < list.length; i++) { /** insert list[i] into a sorted sublist list[0..i-1] so that list[0..i] is sorted. */ double currentElement = list[i]; int k; for (k = i - 1; k >= 0 && list[k] > currentElement; k--) { list[k + 1] = list[k]; } // Insert the current element into list[k+1] list[k + 1] = currentElement; } Insertion Sort InsertSort
92
Since sorting is frequently used in programming, Java provides several overloaded sort methods for sorting. Sort Utility 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);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.