Presentation is loading. Please wait.

Presentation is loading. Please wait.

Spring 2006CISC101 - Prof. McLeod1 Last Time The File class. Back to methods –Passing parameters by value and by reference. –Review class attributes. –An.

Similar presentations


Presentation on theme: "Spring 2006CISC101 - Prof. McLeod1 Last Time The File class. Back to methods –Passing parameters by value and by reference. –Review class attributes. –An."— Presentation transcript:

1 Spring 2006CISC101 - Prof. McLeod1 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.

2 Spring 2006CISC101 - Prof. McLeod2 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!

3 Spring 2006CISC101 - Prof. McLeod3 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.

4 Spring 2006CISC101 - Prof. McLeod4 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.

5 Spring 2006CISC101 - Prof. McLeod5 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!

6 Spring 2006CISC101 - Prof. McLeod6 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.

7 Spring 2006CISC101 - Prof. McLeod7 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!

8 Spring 2006CISC101 - Prof. McLeod8 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.

9 Spring 2006CISC101 - Prof. McLeod9 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?

10 Spring 2006CISC101 - Prof. McLeod10 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?

11 Spring 2006CISC101 - Prof. McLeod11 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…).

12 Spring 2006CISC101 - Prof. McLeod12 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.

13 Spring 2006CISC101 - Prof. McLeod13 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.

14 Spring 2006CISC101 - Prof. McLeod14 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 “<“.

15 Spring 2006CISC101 - Prof. McLeod15 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 int s – 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!

16 Spring 2006CISC101 - Prof. McLeod16 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.

17 Spring 2006CISC101 - Prof. McLeod17 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

18 Spring 2006CISC101 - Prof. McLeod18 2712318117 1227318117 3122718117 3121827117 3 1218277 3711121827

19 Spring 2006CISC101 - Prof. McLeod19 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.

20 Spring 2006CISC101 - Prof. McLeod20 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

21 Spring 2006CISC101 - Prof. McLeod21 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

22 Spring 2006CISC101 - Prof. McLeod22 2712318117 3122718117 3727181112 3711182712 3711122718 3711121827

23 Spring 2006CISC101 - Prof. McLeod23 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.

24 Spring 2006CISC101 - Prof. McLeod24 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.

25 Spring 2006CISC101 - Prof. McLeod25 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

26 Spring 2006CISC101 - Prof. McLeod26 Simple Sorting Algorithms – Bubble Sort – Cont. Note that both the comparison and the swap are inside the inner loop (yuk!).

27 Spring 2006CISC101 - Prof. McLeod27 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

28 Spring 2006CISC101 - Prof. McLeod28 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.

29 Spring 2006CISC101 - Prof. McLeod29 2712318117 3271271811 3727121118 3711271218 3711122718 3711121827

30 Spring 2006CISC101 - Prof. McLeod30 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)

31 Spring 2006CISC101 - Prof. McLeod31 Comparing Sorts, Cont.

32 Spring 2006CISC101 - Prof. McLeod32 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.

33 Spring 2006CISC101 - Prof. McLeod33 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…)

34 Spring 2006CISC101 - Prof. McLeod34 Comparing Sorts, Cont.

35 Spring 2006CISC101 - Prof. McLeod35 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?

36 Spring 2006CISC101 - Prof. McLeod36 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)

37 Spring 2006CISC101 - Prof. McLeod37 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; ”)

38 Spring 2006CISC101 - Prof. McLeod38 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 n 2 for out simple sorts, or n for binsort). See the next slide for a Quicksort method:

39 Spring 2006CISC101 - Prof. McLeod39 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)

40 Spring 2006CISC101 - Prof. McLeod40 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


Download ppt "Spring 2006CISC101 - Prof. McLeod1 Last Time The File class. Back to methods –Passing parameters by value and by reference. –Review class attributes. –An."

Similar presentations


Ads by Google