400 likes | 418 Views
Review class attributes, passing parameters, and file I/O in Java with Prof. McLeod. Learn about variable scope, lifetime, and sorting algorithms. Explore sorting criteria, algorithm selection, memory usage, and sorting efficiency.
E N D
Last Time • The File class. • Back to methods • Passing parameters by value and by reference. • Review class attributes. • An exercise to review File I/O, look at passing by reference and the use of class attributes. CISC101 - Prof. McLeod
Announcements • Assn 3 due this evening. • Final Exam on June 15, 9am. Room TBA. • Lecture exercise “solution” from Tuesday is posted. • Assn 4 posted later today. • Sorting String’s! CISC101 - Prof. McLeod
Today • Variable scope and lifetime. (leftover from Tuesday) • Sorting • Next week: • Searching • Round-off error – sources and effects. • Optional Topics? (applets, building GUI applications, javadoc?) • Final exam review and exercises. CISC101 - Prof. McLeod
Variable Scope • A variable can be declared in five different places, all within a class, from innermost to outermost: • Inside a block ({}), which is contained within a method. • Inside a “for” statement. • Inside a method, but not inside another block. • Inside a parameter list. • Inside a class, at the same “level” as the methods. • A variable is not “known” outside its scope - it is as if the variable were not even declared. CISC101 - Prof. McLeod
Variable Scope - Cont. • Remember: • That it is “wasteful” to declare a variable inside a loop. • If a loop counter is declared in the for statement itself, it is not available outside the loop. • If you try to access the value of a variable outside its scope, you will get an error. • The same variable name cannot be used twice in the same scope. So you cannot declare the same variable name in an inner block, when it already exists in an outer block. • The same variable name can be used in separate (not overlapping) scopes. - Be careful with this as it can cause confusion! CISC101 - Prof. McLeod
Variable Lifetime • Also called “duration”. • When the execution of a program moves out of the scope of a non-static variable, it’s “lifetime” is over. • In Java, it is “garbage collected” automatically. • A static variable or method persists in memory after its first use and is not garbage collected until the program is complete. • Only class attributes and methods can be called static. CISC101 - Prof. McLeod
Sorting - Overview • Suppose you have a collection of “things” – why would you want to sort them? • Imagine a telephone book that was not in order! CISC101 - Prof. McLeod
Sorting – Overview – Cont. • The first step in sorting is to select the criteria used for the sort and the direction of the sort. • It could be ascending numeric order, or alphabetic order by last name, etc. CISC101 - Prof. McLeod
Sorting – Overview – Cont. • The next step is to decide which of the dozens of available sorting algorithms is most appropriate. • Issues: • How large is the dataset? • What will be critical: memory usage or execution time? • Is it necessary that a new element be inserted in order or can it be added at the end and the sort deferred? CISC101 - Prof. McLeod
Sorting – Overview – Cont. • How often will the algorithm be asked to sort a dataset that is already in order, except for a few newly added elements? Or, will it always have to re-sort a completely disordered dataset? • Will the dataset initially be in random order or will it have some order to start with? CISC101 - Prof. McLeod
Sorting – Overview – Cont. • If the dataset is small (< 1000?) then it is often just as easy to stick with a simple sorting algorithm since it will be easier to code and debug, and not too memory intensive. • Sorting algorithms can be compared on the basis of: • The number of comparisons for a dataset of size n, • The number of data movements (“swaps”) necessary, and • How these measures change with n (Analysis of Complexity…). CISC101 - Prof. McLeod
Sorting – Overview – Cont. • Often need to consider the above values for best case (data almost in order), average case (random order), and worst case (reverse order). • Some algorithms behave the same regardless of the state of the data, and others do better depending on how well the data is initially ordered. CISC101 - Prof. McLeod
Sorting – Overview – Cont. • If sorting simple values like integers or key values, then comparisons are easy to carry out and the comparison efficiency of the algorithm may not be as important as the number of data movements. • However, if strings or objects are being compared then the number of comparisons would be better kept to a minimum. • Finally, the only real measure of what algorithm is the best is an actual measure of elapsed time. The initial choice can be based on theory alone, but the final choice for a time-critical application must be by actual experimental measurement. CISC101 - Prof. McLeod
Sorting – Overview – Cont. • I will be presenting code samples that sort arrays of integers (int[] A) into ascending order because this is easiest to understand. • However the logic of the algorithm can be applied directly to arrays or lists of objects, provided the search criteria are specified. • Descending order usually only requires that you change the comparison from “>” to “<“. CISC101 - Prof. McLeod
Aside: Sorting Code on Slides • The code I will show is fairly compact (to run quickly and fit on a slide!). Coding style may be a bit compromised… • It uses A for the variable name for an array of ints – that’s normally not a great variable name to use – but it is short! • There are many ways of expressing these algorithms in code, but you can always tell which algorithm it is! CISC101 - Prof. McLeod
Simple Sorting Algorithms – Insertion Sort • Probably the most “instinctive” kind of sort: Find the location for an element and move all others up one, and insert the element. • Pseudocode: • Loop through array from i=1 to array.length-1, selecting element at position i = temp. • Locate position for temp (position j, where j <= i), and move all elements above j up one location • Put temp at position j. CISC101 - Prof. McLeod
Simple Sorting Algorithms – Insertion Sort – Cont. public static void insertionSort (int[] A) { int temp; int i, j; for (i=1; i < A.length; i++) { temp = A[i]; for (j=i; j>0 && temp < A[j-1]; j--) A[j] = A[j-1]; A[j] = temp; } // end for } // end insertionSort CISC101 - Prof. McLeod
27 12 3 18 11 7 12 27 3 18 11 7 3 12 27 18 11 7 3 12 18 27 11 7 3 11 12 18 27 7 3 7 11 12 18 27 CISC101 - Prof. McLeod
Simple Sorting Algorithms – Selection Sort • This one works by selecting the smallest element and then putting it in its proper location. • Pseudocode: • Loop through the array from i=0 to one element short of the end of the array. • Select the smallest element in the array range from i plus one to the end of the array. • Swap this value with the value at position i. CISC101 - Prof. McLeod
Simple Sorting Algorithms – Selection Sort • First, a “swap” method that will be used by this and other sorts: public static void swap(int[] A, int pos1, int pos2) { int temp = A[pos1]; A[pos1] = A[pos2]; A[pos2] = temp; } // end swap CISC101 - Prof. McLeod
Simple Sorting Algorithms – Selection Sort public static void selectionSort(int[] A) { int i, j, least; for (i = 0; i < A.length-1; i++) { least = i; for (j = i+1; j < A.length; j++) if (A[j] < A[least]) least = j; if (i != least) swap(A, least, i); } // end for } // end selectionSort CISC101 - Prof. McLeod
27 12 3 18 11 7 3 12 27 18 11 7 3 7 27 18 11 12 3 7 11 18 27 12 3 7 11 12 27 18 3 7 11 12 18 27 CISC101 - Prof. McLeod
Simple Sorting Algorithms – Selection Sort – Cont. • The selection sort is “swap efficient”, and the insertion sort can be efficient for datasets that are mostly in order. CISC101 - Prof. McLeod
Simple Sorting Algorithms – Bubble Sort • Is best envisioned as a vertical column of numbers as bubbles. The larger bubbles gradually work their way to the top of the column, with the smaller ones pushed down to the bottom. • Pseudocode: • Loop through array from i=0 to length of array. • Loop down from the last element in the array to i. • Swap adjacent elements if they are in the wrong order. CISC101 - Prof. McLeod
Simple Sorting Algorithms – Bubble Sort – Cont. public static void bubbleSort( int[] A) { int i, j; for (i=0; i < A.length; i++) for (j = A.length-1; j > i; j--) if (A[j] < A[j-1]) swap(A, j, j-1); } // end bubbleSort CISC101 - Prof. McLeod
Simple Sorting Algorithms – Bubble Sort – Cont. • Note that both the comparison and the swap are inside the inner loop (yuk!). CISC101 - Prof. McLeod
Simple Sorting Algorithms – Bubble Sort – A Slight Improvement public static void bubbleSort(int[] A) { int i, j; boolean isDone = false; for (i=0; i < A.length && !isDone; i++) { isDone = true; for (j = A.length-1; j > i; j--) if (A[j] < A[j-1]) { swap(A, j, j-1); isDone = false; } } } // end bubbleSort CISC101 - Prof. McLeod
Simple Sorting Algorithms – Bubble Sort – Cont. • Possibly the simplest sorting algorithm to code. (If you have to commit one to memory, this is it!) • Also the slowest sorting algorithm! • On average, bubble sort makes n times more moves than selection or insertion sort. CISC101 - Prof. McLeod
27 12 3 18 11 7 3 27 12 7 18 11 3 7 27 12 11 18 3 7 11 27 12 18 3 7 11 12 27 18 3 7 11 12 18 27 CISC101 - Prof. McLeod
Comparing Sorts • Based on sorting a given number of int values between 0 and 1,000,000, on my laptop (a Pentium 4 with XP, using Eclipse). • Timings obtained with System.currentTimeMillis() (see code) CISC101 - Prof. McLeod
Comparing Sorts, Cont. CISC101 - Prof. McLeod
Comparing Sorts, Cont. • Best is insertion followed by selection, and worst is bubble sort. • The sorting times actually increase as the square of the size of the dataset. • With more experiments: • Bubble sort is always the worst!! • Insertion sort works best with data that is almost in order, but not quite as well as selection sort for reverse order data. • Selection sort does not care about the state of the data. CISC101 - Prof. McLeod
Comparing Sorts, Cont. • Remember our bin sort from assignment 2? • How does it measure up? • And, let us include another algorithm called “Quicksort” used by Arrays.sort(). • (More about Arrays.sort() in a moment…) CISC101 - Prof. McLeod
Comparing Sorts, Cont. CISC101 - Prof. McLeod
Comparing Sorts, Cont. • That’s a very dramatic difference! What is going on here? Any ideas as to why binsort is so fast? • What is the limitation of binsort – why not use it to sort everything? • What about this other sort – Quicksort? Wow!! CISC101 - Prof. McLeod
Aside - Sorting in java.util • Java provides “canned” sorting methods for arrays. • The java.util.Arrays class has static methods for arrays of each of the primitive types (except boolean). • For example, the methods for arrays of integers are: public static void sort(int[] a) public static void sort(int[] a, int first, int last) CISC101 - Prof. McLeod
Sorting in java.util – Cont. • The latter method call is used to sort a range in the array a. • So, a command like Arrays.sort(A); will sort the array A in ascending order. • (Assuming you have done an “import java.utils.Arrays;”) CISC101 - Prof. McLeod
Sorting in java.util – Cont. • You are not responsible for this: • All of these Arrays.sort() sorting methods utilize a Quicksort algorithm. • Quicksort is a recursive algorithm. • Its speed of execution increases as nlog(n), where n is the size of the dataset (as opposed to n2 for out simple sorts, or n for binsort). • See the next slide for a Quicksort method: CISC101 - Prof. McLeod
public static void quickSort (int[] A, int first, int last) { int lower = first + 1; int upper = last; swap(A, first, (first+last)/2); int pivot = A[first]; while (lower <= upper) { while (A[lower] < pivot) lower++; while (A[upper] > pivot) upper--; if (lower < upper) swap(A, lower++, upper--); else lower++; } swap(A, upper, first); if (first < upper - 1) quickSort(A, first, upper-1); if (upper + 1 < last) quickSort(A, upper+1, last); } // end quickSort(subarrays) CISC101 - Prof. McLeod
Sorting Animations • For a collection of animation links see: http://www.hig.no/~algmet/animate.html • Here are a couple that I liked: http://www.cs.pitt.edu/~kirk/cs1501/animations/Sort3.html http://cs.smith.edu/~thiebaut/java/sort/demo.html CISC101 - Prof. McLeod