Download presentation
Presentation is loading. Please wait.
Published byValerie Baker Modified over 8 years ago
1
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer
2
QUIZ # 1 WHEN: WEDNESDAY 2/10 POINTS: 4 CLOSED BOOK / CLOSED NOTES NO LAPTOPS ALLOWED. NO FLASH DRIVES ALLOWED. 2
3
WHAT TO STUDY TEXT CHAPTERS 7 CHAPTER 8 LECTURES 1 THROUGH 3 Labs Assignments and Extra credit exercises 3
4
Format Entire class period. Closed Book/ Closed Notes Be able to write a program that acts as a template (service) class. Be able to write a Client class. Know how to create and use: Constructors Accessor/mutator methods Arrays of primitive data types / Arrays of objects Equals method toString method. StringTokenizer Scanner to read user input from DOS Scanner to read text files. Command line input from user. NumberFormat and DecimalFormat classes. Create a package for your classes. Usage of enumerations. Packaging of classes involved. 4
5
Questions Sorting is not part of this quiz. Grade: 4 points towards your final grade. Note: Not packaging at least one class using the proper command will cost you 0.6 points. You will use Notepad++ to write the program and edit it. You will zip your files (do not rar or 7z). Name the zipped folder with your name. Submit it to Blackboard under folder QUIZ 1. 5
6
Suggestions Type code first and then worry bout compiler errors. You can get a good grade even if there are minor compiler errors as long as your code makes sense. 6
7
Topics Sorting Algorithm Selection Sort Binary Search Vectors (if time permits) Multi-Dimensional Arrays (if time permits)
8
Sequential Search To find the first occurrence of a key in an array of size n. (remember that the size an array is provided by its “length” attribute ) Go through each element one by one Compare each element with the key Check if the element is equal to the key. If you find a match, return the index of the element If you do not find a match in the array, return -1. How many comparisons are need to find a match? Best Case: ? The key is found in index 0 (first element in the array) No. of comparison needed is 1 Worst Case: ? The key is found in index (n – 1) (last element in the array) The key is not found in the array No. of comparison needed is n
9
Sequential Search Sequential search algorithm performs worst when the key is not found in the array. Is there a way we can make sequential search more efficient with this case? How about if we arrange the array in a decreasing or increasing order? The ordering of the elements in the array is called sorting.
10
Sorting 12167234311298925 11112232529436789 12167234311298925 89674329252312111 Sorting (increasing order) Sorting (decreasing order) *In this class, unless mentioned, sorting means sorting in increasing order
11
Sorting an Array When an array's elements are in random order, our Sequential Search method needs to look at every element in the array before discovering that the search key is not in the array. This is inefficient; the larger the array, the more inefficient a Sequential Search becomes. We could simplify the search by arranging the elements in numeric order, which is called sorting the array. Once the array is sorted, we can use various search algorithms to speed up a search. If the search key is not in the array, we can detect that condition when we find a value that is higher than the search key. All elements past that position will be greater than the value of that element, and therefore, greater than the search key. 11
12
A Simple Sorting Strategy* What does a sorted array look like? Largest item Second Largest item We know the algorithm to find maximum value in an array Can we use this idea? Nth largest item
13
Selection Sort Suppose we want to sort from smallest to largest element in the array. In a Selection Sort, we make one pass through the array and select the largest element in the array and place it at the end of the array. Then we make another pass through the array up to index=length-2 this time and select the next- largest element and put it in the next-to-last position in the array, and so on. To do this, we consider the unsorted portion of the array as a subarray. – We repeatedly select the largest value in the current subarray and move it to the end of the subarray, then consider a new subarray by eliminating the elements that are in their sorted locations. – We continue until the subarray has only one element. At that time, the array is sorted. 13
14
Selection Sort Example In the beginning, the entire array is the unsorted subarray : We swap the largest element with the last element: 14
15
Selection Sort Example (cont’d) Again, we swap the largest element and the last element : When there is only one unsorted element, the array is completely sorted: 15
16
The Selection Sort Algorithm To sort an array with n elements in ascending order: 1. Consider the n elements as a subarray with m = n elements 2. Find the index of the largest value in this subarray 3. Swap the values of the element with the largest value and the element in the last position in the subarray 4. Consider a new subarray of m = m - 1 elements by eliminating the last element in the previous subarray 5. Repeat steps 2 through 4 until m = 1 16
17
Sorting Arrays of Objects In arrays of objects, the array elements are object references. Thus, to sort an array of objects, we need to sort the data of the objects. Usually, one of the instance variables of the object acts as a sort key. For example, in an email object, the sort key might be the date received. 17
18
Code for Selection Sort Declarations import java.util.*; import java.io.*; public class SelectionSort { public static void main(String[] args) { int i=0; int count=0; int index=0; int array []=new int[10]; //notice that we have assumed that there are 10 numbers in the file. Otherwise we have to count the numbers in the file and set the size of the array accordingly. int temp; int subarraylength=0; 18
19
Code for Selection Sort– Read the numbers from a file and place in array Notice that we have assumed that we know the size of the file (the number of numbers)!!! try { File file=new File(args[0]); Scanner scanner=new Scanner(file); i=scanner.nextInt(); array[count]=i; //first element at index 0 has been entered. while(scanner.hasNext()) { count++; i=scanner.nextInt(); array[count]=i; } catch (IOException e){System.out.println(“Error reading the file”); } 19
20
Code for Selection Sort– Algorithm for (int j=0; j<=array.length-1; j++ ) //we are going to go through the array size-1 times. { subarraylength=array.length-j; // now find index of largest element in subarray index=0; for (int k=1; k<subarraylength; k++){ if (array[k] > array[index]){ index=k; } // Now swap array elements temp=array[index]; array[index]=array[array.length-j-1]; array[array.length-j-1]=temp; }//end top for 20
21
Code for Selection Sort– Algorithm //Read the array now. The elements should be sorted. for (int g=0; g<array.length ; g++){ System.out.println(+array[g]); } }//end main }// end of class 21
22
Sorting Objects By a Field’s Value Change the comparison from the previous slides so that it is now: If(array[k].getFieldName()>array[index].getFieldName()) ………………………………….. Be careful with the swapping part of the algorithm also.. temp variable will have to be of the class type that is stored in the array i.e VehicleA temp; 22
23
Number of Comparisons Suppose the unsorted array size= n First pass (comparisons) is n-1 Next pass is n-2 Next pass is n-3 and so on. Total number of passes (comparisons) is: n ( n-1) / 2 Thus if n=10 numbers of passes: 10*(10-1)/2 = 45 23
24
Binary Search A Binary Search is like the "Guess a Number" game. To guess a number between 1 and 100, we start with 50 (halfway between the beginning number and the end number). If we learn that the number is greater than 50, we immediately know the number is not 1 - 49. If we learn that the number is less than 50, we immediately know the number is not 51 - 100. We keep guessing the number that is in the middle of the remaining numbers (eliminating half the remaining numbers) until we find the number. 24
25
Binary Search The "Guess a Number" approach works because 1 - 100 are a "sorted" set of numbers. To use a Binary Search, the array must be sorted. Our Binary Search will attempt to find a search key in a sorted array. If the search key is found, we return the index of the element with that value. If the search key is not found,we return -1. 25
26
The Binary Search Algorithm We begin by comparing the middle element of the array and the search key. If they are equal, we found the search key and return the index of the middle element. If the middle element's value is greater than the search key, then the search key cannot be found in elements with higher array indexes. So, we continue our search in the left half of the array. If the middle element's value is less than the search key, then the search key cannot be found in elements with lower array indexes. So, we continue our search in the right half of the array. 26
27
The Binary Search Algorithm (cont’d) As we keep searching, the subarray we search keeps shrinking in size. In fact, the size of the subarray we search is cut in half at every iteration. If the search key is not in the array, the subarray we search will eventually become empty. At that point, we know that we will not find our search key in the array, and we return –1. 27
28
Value1223375665899199102 Index012345678 Key Start= End= Mid=(Start+End)/2= Is Array[Mid]==Key? 12233756 0123 899199102 5678 12 0 3756 23 89 5 99102 78 56 3 102 8 Start= End= Mid=(Start+End)/2= Is Array[Mid]==Key? Start= End= Mid=(Start+End)/2= Is Array[Mid]==Key? Start= End= Mid=(Start+End)/2= Is Array[Mid]==Key?
29
Value1223375665899199102 Index012345678 Key Start= End= Mid=(Start+End)/2= Is Array[Mid]==Key? 12233756 0123 899199102 5678 12 0 3756 23 89 5 99102 78 56 3 102 8 Start= End= Mid=(Start+End)/2= Is Array[Mid]==Key? Start= End= Mid=(Start+End)/2= Is Array[Mid]==Key? Start= End= Mid=(Start+End)/2= Is Array[Mid]==Key?
30
Example of a Binary Search We will search for the value 7 in this sorted array: To begin, we find the index of the center element, which is 8, and we compare our search key (7) with the value 45. 30
31
Binary Search Example (cont’d) Because 7 is less than 45, we eliminate all array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search. The index of the center element is now 3, so we compare 7 to the value 8. 31
32
Binary Search Example (cont’d) Because 7 is less than 8, we eliminate all array elements higher than our current middle element (3) and make elements 0 through 2 the new subarray to search. The index of the center element is now 1, so we compare 7 to the value 6. 32
33
Binary Search: Finding the Search Key Because 7 is greater than 6, we eliminate array elements lower than our current middle element (1) and make element 2 the new subarray to search. The value of element 2 matches the search key, so our search is successful and we return the index 2. 33
34
Binary Search Code public int binarySearch( int [] array, int key ) { int start = 0, end = array.length - 1; while ( end >= start ) { int middle = ( start + end ) / 2; if ( array[middle] == key ) return middle; // key found else if ( array[middle] > key ) end = middle - 1; // search left else start = middle + 1; // search right } return -1; // key not found } Note: Assumes that the items are sorted from smaller to largest. 34
35
Value1223375665899199102 Index012345678 Key 12233756 0123 899199102 5678 12 0 3756 23 89 5 99102 78 56 3 102 8
36
Using Arrays as Counters To count multiple items, we can use an array of integers. Each array element is a counter Example: we want to throw a die and count the number of times each side is rolled We set up an array of 6 integer counters, initialized to 0 For each roll, we use ( roll - 1 ) as the index of the array element to increment 36
37
Example Code // instantiate array of counters int [] rollCount = new int [6]; // roll the die NUMBER_OF_ROLLS times for ( int i = 1; i <= NUMBER_OF_ROLLS; i++ ) { // roll the die int roll = (int) Math.random( ) * 6 + 1; // increment the corresponding counter rollCount[roll - 1]++; } See Examples 8.22 Die.java, 8.23 DieCount.java 37
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.