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

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Math 130 Introduction to Computing Sorting Lecture # 17 10/11/04 B Smith: Save until Week 15? B Smith: Save until Week 15? B Smith: Skipped Spring 2005?
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Sorting. “Sorting” When we just say “sorting,” we mean in ascending order (smallest to largest) The algorithms are trivial to modify if we want to sort.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
CSE 373: Data Structures and Algorithms
CSE 373: Data Structures and Algorithms
Simple Sorting Algorithms
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
Quicksort.
Sorting Algorithms: Selection, Insertion and Bubble.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CSSE221: Software Dev. Honors Day 22 Announcements Announcements No written part to Homework 8 No written part to Homework 8 You can focus on Simulation.
Algorithm Efficiency and Sorting
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
EFFICIENCY & SORTING CITS1001. Listen to the sound of sorting Various algorithms Quicksort
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Winter 2006CISC121 - Prof. McLeod1 Stuff Assn 5 is available and due Monday, 7pm. Pre-exam tutorial time. (Exam is April 27). April 18, room TBA. Office.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
CSE 373 Data Structures and Algorithms
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
Comparison-Based Sorting & Analysis Smt Genap
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
3 – SIMPLE SORTING ALGORITHMS
Lecture #9: Sorting Algorithms خوارزميات الترتيب Dr. Hmood Al-Dossari King Saud University Department of Computer Science 22 April 2012.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
21/3/00SEM107 - © Kamin & ReddyClass 14 - Sorting - 1 Class 14 - Review: Sorting & searching r What are sorting and searching? r Simple sorting algorithms.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 9 Last time: –Finished Linked Lists –Stacks & Queues.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Intro To Algorithms Searching and Sorting. Searching A common task for a computer is to find a block of data A common task for a computer is to find a.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Winter 2006CISC121 - Prof. McLeod1 Stuff No stuff today!
COP 3540 Data Structures with OOP
Spring 2006CISC101 - Prof. McLeod1 Announcements Assn 4 is posted. Note that due date is the 12 th (Monday) at 7pm. (Last assignment!) Final Exam on June.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Copyright © 2014 Curt Hill Algorithms From the Mathematical Perspective.
SORTING Sorting is storage of data in some order, it can be in ascending or descending order. The term Sorting comes along-with the term Searching. There.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Assignment 5 is posted. Exercise 8 is very similar to what you will be doing with assignment 5. Exam.
Chapter 9: Sorting and Searching Arrays
Sorting Mr. Jacobs.
Recitation 13 Searching and Sorting.
Simple Sorting Algorithms
Linear and Binary Search
Describing algorithms in pseudo code
Winter 2018 CISC101 11/19/2018 CISC101 Reminders
Winter 2018 CISC101 12/2/2018 CISC101 Reminders
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Sorting … and Insertion Sort.
CISC124 Labs start this week in JEFF 155. Fall 2018
Simple Sorting Algorithms
CSE 373 Sorting 1: Bogo Sort, Stooge Sort, Bubble Sort
Simple Sorting Algorithms
Simple Sorting Algorithms
Sorting Popular algorithms:
Presentation transcript:

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.

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!

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.

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.

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!

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.

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!

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.

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?

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?

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…).

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.

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.

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 “<“.

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!

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.

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

Spring 2006CISC101 - Prof. McLeod

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.

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

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

Spring 2006CISC101 - Prof. McLeod

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.

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.

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

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

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

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.

Spring 2006CISC101 - Prof. McLeod

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)

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

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.

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…)

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

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?

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)

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; ”)

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:

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)

Spring 2006CISC101 - Prof. McLeod40 Sorting Animations For a collection of animation links see: Here are a couple that I liked: