COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
-
Upload
crystal-joseph -
Category
Documents
-
view
226 -
download
2
Transcript of COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
COP3502 Programming Fundamentals for CIS Majors 1
Instructor: Parisa Rashidi
Chapter 5 Methods Memory management Variable scope
Last Week
Chapter 6 Arrays
DeclarationInitializationAccessCommon operations
Summing all entries, max, min, … for-each loop Variable length argument list Linear search, binary search Sorting
Objectives
Arrays
Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Declaring 100 integer variables?
Motivation
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
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 6Value of
element at index 6
First approach:
Example:
Second approach (possible, but not preferred):
Example:
Declaring Array
datatype[] arrayRefVar;
double[] myList;
datatype arrayRefVar[];
double myList[];
Example:
Creating Array
arrayRefVar = new datatype[arraySize];
//two stepsdouble[] myList;myList = new double[10];
//one stepdouble[] myList= new double[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;
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
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
Each element of array is an indexed variable:
Example (accessing first element)
Indexed Variables
arrayRefVar[index];
myList[0];
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;
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};
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];
Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Program
AnalyzeNumbers Run
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
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.
After the array is created
0
1
2
3
4
0
0
0
0
0
Values
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
After the array is created
0
1
2
3
4
0
0
0
0
0
Values
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
After the array is created
0
1
2
3
4
0
0
0
0
0
Values
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
After the array is created
0
1
2
3
4
0
1
0
0
0
Values
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
After the array is created
0
1
2
3
4
0
1
0
0
0
Values
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
After the array is created
0
1
2
3
4
0
1
0
0
0
Values
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
After the array is created
0
1
2
3
4
0
1
3
0
0
Values
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
After the array is created
0
1
2
3
4
0
1
3
0
0
Values
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
After the array is created
0
1
2
3
4
0
1
3
0
0
Values
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)
After the array is created
0
1
2
3
4
0
1
3
6
0
Values
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
After the array is created
0
1
2
3
4
0
1
3
6
0
Values
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
After the array is created
0
1
2
3
4
0
1
3
6
0
Values
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)
After the array is created
0
1
2
3
4
0
1
3
6
10
Values
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
After the array is created
0
1
2
3
4
0
1
3
6
10
Values
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
After the array is created
0
1
2
3
4
0
1
3
6
10
Values
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)
After the array is created
0
1
2
3
4
11
1
3
6
10
Values
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
After the array is created
0
1
2
3
4
11
1
3
6
10
Values
PA3 was posted on FridayPoll on Sakai
Announcement
Chapter 5 Methods Memory management Variable scope
Chapter 6 Array
Last Week
Initializing arrays with input values
Example
Scanner input = new Scanner(System.in);
for (int i = 0; i < myList.length; i++) myList[i] = input.nextDouble();
Initializing arrays with random values
Example
for (int i = 0; i < myList.length; i++) { myList[i] = Math.random() * 100;}
Printing arrays
Example
for (int i = 0; i < myList.length; i++) System.out.print(myList[i] + " ");
Summing all elements
Example
double total = 0;for (int i = 0; i < myList.length; i++) total += myList[i];
Finding the largest element
Example
double max = myList[0];
for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i];}
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;}
myList
[0] [1]
.
.
.
[index]
A random index
i
swap
Shifting Elements
Example
double temp = myList[0]; // Retain the first element // Shift elements leftfor (int i = 1; i < myList.length; i++) { myList[i - 1] = myList[i];} // Move the first element to fill in the last positionmyList[myList.length - 1] = temp;
myList
for-each Loops
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) …
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
RunLotto Numbers Sample Data
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 cardsfor (int i = 0; i < deck.length; i++) deck[i] = i;
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
Program
0 . . .
12 13 . . .
25 26 . . .
38 39 . . .
51
13 Spades (? )
13 Hearts (? )
13 Diamonds (?)
13 Clubs (? )
0 . . .
12 13 . . .
25 26 . . .
38 39 . . .
51
deck [0] . . .
[12] [13]
.
.
. [25] [26]
.
.
. [38] [39]
.
.
. [51]
Random shuffle
6 48 11 24 . . . . . . . . . . . . . . . .
deck [0] [1] [2] [3] [4] [5] . . .
[25] [26]
.
.
. [38] [39]
.
.
. [51]
Card number 6 is 7 of Spades
Card number 48 is 10 of Clubs
Card number 11 is Queen of Spades
Card number 24 is Queen of Hearts
Array Copy
Arrays are reference type, so be careful!
After assignment, both lists will point to the same memory location.
Array Copy
list2 = list1;
Contents of list1
list1
Contents of list2
list2
Before the assignment list2 = list1;
Contents of list1
list1
Contents of list2
list2
After the assignment list2 = list1;
Garbage
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];
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);
Passing Array
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
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
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
Midterm examRegular class time on Feb. 27In the class (PUGH 170)Based on the materials in the
lectures notes, textbook, homeworkTextbook: chapters 1, 2, 3, 4, 5, 6Lecture notes: 1, 2, 3, 4, 5, 6
Announcements
Exam review session Next week: Wednesday or Friday
No homework this weekPoll closing on Monday, vote!
Announcements
Objective: Demonstrate differences of passing primitive data type variables and array variables.
Program
TestPassArray Run
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 1 2 3 4 5 6
result 6 5 4 3 2 1
Generate 100 lowercase letters randomly and assign to an array of characters. Count the occurrence of each letter in the array.
Program
CountLettersInArray Run
Variable-Length Argument Lists
You can pass a variable number of arguments to a method
Type should be followed by an ellipsis (…)
Variable Length args
Typename … parameterName
Only one variable-length argument in each method
Must be the last parameter
Variable Length args
Java treats it like an arrayYou can use An array or The variable-length argument
list
Variable Length args
Problem: finding the maximum in a list of unspecified number of values
Variable Length args
VargArgsDemo Run
Searching & Sorting
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
Example
Search
list
key Compare key with list[i] for i = 0, 1, …
[0] [1] [2] …
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; }}
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
Illustration of linear search
Linear Search
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
3
3
3
3
3
3
Key List
Array Search
Linear search Binary search
Sort Selection sort Insertion sort
Previously
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
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
Example
Binary Search
1 2 3 4 6 7 8 9
1 2 3 4 6 7 8 9
1 2 3 4 6 7 8 9
8
8
8
Key List
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;}
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'));
More? “The Art of Computer
Programming” by Donald Knuth.
Search & Sort
We will look at two different types of sorting
Selection sort Insertion sort
Sorting
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
Selection Sort
2 9 5 4 8 1 6
swap
Select 1 (the smallest) and swap it with 2 (the first) in the list
1 9 5 4 8 2 6
swap
The number 1 is now in the correct position and thus no longer needs to be considered.
1 2 5 4 8 9 6
swap
1 2 4 5 8 9 6
Select 2 (the smallest) and swap it with 9 (the first) in the remaining list
The number 2 is now in the correct position and thus no longer needs to be considered.
Select 4 (the smallest) and swap it with 5 (the first) in the remaining list
The number 6 is now in the correct position and thus no longer needs to be considered.
1 2 4 5 8 9 6
Select 6 (the smallest) and swap it with 8 (the first) in the remaining list
1 2 4 5 6 9 8
swap
The number 6 is now in the correct position and thus no longer needs to be considered.
1 2 4 5 6 8 9
Select 8 (the smallest) and swap it with 9 (the first) in the remaining list
The number 8 is now in the correct position and thus no longer needs to be considered.
Since there is only one element remaining in the list, sort is completed
5 is the smallest and in the right position. No swap is necessary
The number 5 is now in the correct position and thus no longer needs to be considered.
swap
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;}
//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; } }
// if list[i] is in its correct position
Selection Sort
if (currentMinIndex != i) { list[currentMinIndex] = list[i]; list[i] = currentMin; }
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
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
int[] myList = {2, 9, 5, 4, 8, 1, 6};
2 9 5 4 8 1 6
Step 1: Initially, the sorted sublist contains the first element in the list. Insert 9 to the sublist.
2 9 5 4 8 1 6
Step2: The sorted sublist is {2, 9}. Insert 5 to the sublist.
2 5 9 4 8 1 6
Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to the sublist.
2 4 5 9 8 1 6
Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8 to the sublist.
2 4 5 8 9 1 6
Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert 1 to the sublist.
1 2 4 5 8 9 6
Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}. Insert 6 to the sublist.
1 2 4 5 6 8 9
Step 7: The entire list is now sorted
Insertion Sort
Example: int[] myList = {2, 9, 5, 4, 8, 1,
6};
Insertion Sort
2 9 5 4 8 1 62 9 5 4 8 1 6
2 5 9 4 8 1 6
2 4 5 8 9 1 61 2 4 5 8 9 6
2 4 5 9 8 1 6
1 2 4 5 6 8 9
InsertSort
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
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);