Searching and Sorting 14ACEHRPT Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented.

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

Garfield AP Computer Science
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
6-1 CM0551 Week 6 The Array Data Structure Properties of arrays and subarrays – recap. Sorting: insertion, quick-sort and their time and space complexity.
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
Sorting Algorithms and Average Case Time Complexity
Quicksort Divide-and-Conquer. Quicksort Algorithm Given an array S of n elements (e.g., integers): If array only contains one element, return it. Else.
 1 Sorting. For computer, sorting is the process of ordering data. [ ]  [ ] [ “Tom”, “Michael”, “Betty” ]  [ “Betty”, “Michael”,
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
Chapter 11 Sorting and Searching. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Examine the linear search and.
Spring 2010CS 2251 Sorting Chapter 8. Spring 2010CS 2252 Chapter Objectives To learn how to use the standard sorting methods in the Java API To learn.
Quicksort.
Sorting Chapter 10.
Sorting Chapter 10. Chapter 10: Sorting2 Chapter Objectives To learn how to use the standard sorting methods in the Java API To learn how to implement.
CSE 373 Data Structures Lecture 19
(c) , University of Washington
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 10 Sorting and Searching.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sorting and Searching.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Chapter 14 Searching and Sorting Section 1 - Sequential or Linear Search Section 2 - Binary Search Section 3 - Selection Sort Section 4 - Insertion Sort.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Chapter 9 Searching and Sorting
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Comparison-Based Sorting & Analysis Smt Genap
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2.Solve smaller instances.
Algorithms Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
© 2004 Goodrich, Tamassia Quick-Sort     29  9.
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.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
M180: Data Structures & Algorithms in Java Sorting Algorithms Arab Open University 1.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.
Sorting Ordering data. Design and Analysis of Sorting Assumptions –sorting will be internal (in memory) –sorting will be done on an array of elements.
CS 367 Introduction to Data Structures Lecture 11.
Intro. to Data Structures Chapter 7 Sorting Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Chapter 7 Sorting Sort is.
Sorting – Lecture 3 More about Merge Sort, Quick Sort.
Building Java Programs Chapter 13 Sorting reading: 13.3, 13.4.
Searching and Sorting Searching algorithms with simple arrays
Sorting Mr. Jacobs.
Subject Name: Design and Analysis of Algorithm Subject Code: 10CS43
Comparing Objects in Java
Ch 14: Search and Sorting Yonglei Tao.
Chapter 13: Searching and Sorting
Advanced Sorting Methods: Shellsort
Building Java Programs
Selection Insertion and Merge
24 Searching and Sorting.
Sorting Chapter 8 CS 225.
CSE 373 Data Structures and Algorithms
Sorting Taking an arbitrary permutation of n items and rearranging them into total order Sorting is, without doubt, the most fundamental algorithmic.
Advanced Sorting Methods: Shellsort
Presentation transcript:

Searching and Sorting 14ACEHRPT Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin 2nd AP edition  with GridWorld

14-2 Objectives: Learn about the three ways to compare objects in Java Learn the following algorithms  Sequential and Binary Search  Selection Sort and Insertion Sort  Mergesort and Quicksort Learn about the java.util.Arrays and java.util.Collections classes

14-3 Comparing Objects in Java boolean result = obj1.equals(obj2); int diff = obj1.compareTo(obj2); int diff = c.compare(obj1, obj2);

14-4 obj1.equals(obj2) The boolean method equals comes from the class Object: Object’s equals is not very useful: compares addresses of objects Programmers often override equals in their classes public boolean equals(Object other) {... }

14-5 obj1.equals(obj2) (cont’d) public class Pet { private String name;... public boolean equals (Object other) { if (other != null) return name.equals(((Pet)other).name); else return false; } Or: if (other instanceof Pet) instanceof is a boolean operator in Java

14-6 obj1.equals(obj2) (cont’d) equals is called polymorphically from library methods, such as ArrayList’s contains or indexOf  that is why we have to properly override Object’s equals. The equals method is properly defined in String, Integer, Double, etc.

14-7 obj1.compareTo(obj2) compareTo is an abstract method defined in the java.util.Comparable interface: Returns a positive integer if obj1 is “greater than” obj2, a negative integer if obj1 is “less than” obj2, zero if they are “equal.” public int compareTo (T other); Sort of like obj1 - obj2 T is the type parameter

14-8 obj1.compareTo(obj2) (cont’d) public class Pet implements Comparable { private String name;... public int compareTo(Pet other) { return name.compareTo(other.name); } public boolean equals(Object other) { return other instanceof Pet && compareTo((Pet)other) == 0; } equals is not required by Comparable, but it is a good idea to provide it and make it agree with compareTo

14-9 obj1.compareTo(obj2) (cont’d) compareTo is called polymorphically from library methods, such as Arrays.binarySearch(Object[ ] arr). Objects of classes that implement Comparable are called “comparable” (pronounced com-'parable). Strings, Integers, Doubles are comparable.

14-10 obj1.compareTo(obj2) (cont’d) «interface» Comparable String compareTo is based on lexicographical order «interface» Comparable «interface» Comparable IntegerDouble compareTo is based on numerical values

14-11 compare(obj1, obj2) compare is an abstract method defined in the java.util.Comparator interface: Returns a positive integer if obj1 is “greater than” obj2, a negative integer if obj1 is “less than” obj2, zero if they are “equal.” public int compare (T obj1, T obj2); Sort of like obj1 - obj2 T is the type parameter

14-12 compare (obj1, obj2) (cont’d) public class PetComparatorByName implements Comparator {... public int compare (Pet pet1, Pet pet2) { return pet1.getName(). compareTo(pet2.getName()); }

14-13 compare(obj1, obj2) (cont’d) A programmer can define different comparators to be used in different situations. compare is called from library methods, such as Arrays.sort(T [ ] arr, Comparator c) (or from your own methods) that take a comparator object as a parameter.

14-14 Sequential Search Scans the list comparing the target value to each element. Amy 5 Ben 3 Cal 2 Dan 0 Eve 6 Fay 1 Guy 4 Amy? Amy!

14-15 Sequential Search (cont’d) public int sequentialSearch(Object [ ] arr, Object value) { for (int i = 0; i < arr.length ; i++) { if (value.equals(arr [i])) return i; } return  1; } For primitive data types it is if (value == arr [ i ])

14-16 Sequential Search (cont’d) The average number of comparisons (assuming the target value is equal to one of the elements of the array, randomly chosen) is about n / 2 (where n = arr.length). Worst case: n comparisons. Also n comparisons are needed to establish that the target value is not in the array. We say that this is an O(n) (order of n) algorithm.

14-17 Binary Search The elements of the list must be arranged in ascending (or descending) order. The target value is always compared with the middle element of the remaining search range. We must have random access to the elements of the list (an array or ArrayList are OK).

14-18 Binary Search (cont’d) Fay 5 Dan 3 Cal 2 Amy 0 Guy 6 Ben 1 Eve 4 Eve? Fay 5 Dan 3 Cal 2 Amy 0 Guy 6 Ben 1 Eve 4 Fay 5 Dan 3 Cal 2 Amy 0 Guy 6 Ben 1 Eve 4 Eve?Eve!

14-19 Binary Search (cont’d) Recursive implementation: public int binarySearch (int [ ] arr, int value, int left, int right) { if (right < left) return  1; // Not found int middle = (left + right) / 2; if (value == arr [middle] ) return middle; else if (value < arr[middle]) return binarySearch (arr, value, left, middle  1); else // if ( value > arr[middle]) return binarySearch (arr, value, middle + 1, right); }

14-20 Binary Search (cont’d) Iterative implementation: public int binarySearch (int [ ] arr, int value, int left, int right) { while (left <= right) { int middle = (left + right) / 2; if ( value == arr [middle] ) return middle; else if ( value < arr[middle] ) right = middle - 1; else // if ( value > arr[middle] ) left = middle + 1; } return  1; // Not found }

14-21 Binary Search (cont’d) A “divide and conquer” algorithm. Works very fast: only 20 comparisons are needed for an array of 1,000,000 elements; (30 comparisons can handle 1,000,000,000 elements; etc.). We say that this is an O(log n) algorithm.

14-22 Sorting To sort means to rearrange the elements of a list in ascending or descending order. Examples of sorting applications:  a directory of files sorted by name or date  bank checks sorted by account #  addresses in a mailing list sorted by zip code  hits found by a search engine sorted by relevance  credit card transactions sorted by date

14-23 Sorting (cont’d) The algorithms discussed here are based on “honest” comparison of values stored in an array. No tricks. How fast can we sort an array of n elements?  If we compare each element to each other we need n(n-1) / 2 comparisons (that is, n 2 by the “order of magnitude.”)  Faster “divide and conquer” sorting algorithms need approximately n·log 2 n comparisons (much better).

14-24 Sorting (cont’d) n Time n2n2 n log 2 n n n ,000 1,000,000 n log 2 n ,000

14-25 Selection Sort 1. Select the max among the first n elements: 2. Swap it with the n-th element : 3. Decrement n by 1 and repeat from Step 1 (while n > 1) n n n

14-26 Selection Sort (cont’d) Iterative implementation: public void selectionSort (double [ ] arr, int n) { while (n > 1) { int maxPos = 0; for (int k = 1; k < n; k++) if (arr [k] > arr [maxPos] ) maxPos = k; double temp = arr [maxPos]; arr [maxPos] = arr [n  1]; arr [n  1] = temp; n  ; } swap a[maxPos] and a[n-1]

14-27 Selection Sort (cont’d) The total number of comparisons is always (n-1) + (n-2) = n(n-1) / 2 No average, best, or worst case — always the same. An O(n 2 ) algorithm.

14-28 Insertion Sort 1. k = 1; keep the first k elements in order. 2. Take the (k+1)-th element and insert among the first k in the right place. 3. Increment k by 1; repeat from Step 2 (while k < n) k k

14-29 Insertion Sort (cont’d) Iterative implementation: public void insertionSort (double [ ] arr, int n) { for (int k = 1 ; k < n; k++) { double temp = arr [ k ]; int i = k; while (i > 0 && arr [i-1] > temp) { arr [i] = arr [i - 1]; i --; } arr [i] = temp; } shift to the right

14-30 Insertion Sort (cont’d) The average number of comparisons is roughly half of the number in Selection Sort. The best case is when the array is already sorted: takes only (n-1) comparisons. The worst case is n(n-1) / 2 when the array is sorted in reverse order. On average, an O(n 2 ) algorithm.

14-31 Mergesort 1. Split the array into two roughly equal “halves.” 2. Sort (recursively) each half using... Mergesort. 3. Merge the two sorted halves together The smaller value goes first 31 2

14-32 Mergesort (cont’d) public void mergesort (double[ ] arr, int from, int to) { if (from <= to) return; int middle = (from + to ) / 2; mergesort (arr, from, middle); mergesort (arr, middle + 1, to); if (arr [middle] > arr [middle + 1]) { copy (arr, from, to, temp) ; merge (temp, from, middle, to, arr); } double[ ] temp is initialized outside the mergesort method Optional shortcut: “if not yet sorted”... Base case

14-33 Mergesort (cont’d) Takes roughly n·log 2 n comparisons. Without the shortcut, there is no best or worst case. With the optional shortcut, the best case is when the array is already sorted: takes only (n - 1) comparisons. An O(n log n) algorithm.

14-34 Quicksort 1. Pick one element, called “pivot” 2. Partition the array, so that all the elements to the left of pivot are  pivot; all the elements to the right of pivot are  pivot. 3.Sort recursively the left and the right segments using... Quicksort

14-35 Quicksort (cont’d) Takes roughly n·log 2 n comparisons. May get slow if pivot consistently fails to split the array into approximately equal halves. An O(n log n) algorithm.

14-36 The Benchmarks program Enter the array size Running time in milliseconds Choose the sorting algorithm

14-37 java.util.Random Benchmarks uses the java.util.Random class — a more controlled way to generate random numbers. Constructors: If we set the same seed, we get the same “random” sequence. Random generator1 = new Random(); Random generator2 = new Random(seed); long seed; the seed is different each time

14-38 java.util.Random (cont’d) Methods: int k = generator.nextInt (n); double x = generator.nextDouble (); 0  k < n 0  x < 1

14-39 java.util.Arrays Provides static methods for dealing with arrays. Works for arrays of numbers, Strings, and Objects. Methods: int pos = Arrays.binarySearch (arr, target); Arrays.sort (arr); Arrays.fill (arr, value); // fills arr with a given value String str = Arrays.toString(arr); Arrays.asList(arr); Returns a representation of arr as a fixed-length list

14-40 java.util.Collections Provides static methods for dealing with ArrayLists and other Java collections. Works for arrays of numbers, Strings, and Objects. Methods: int pos = Collections.binarySearch (list, target); Collections.sort (list); Collections.shuffle (list);

14-41 Review: What is the type of the parameter in the equals method? How many methods are listed in the Comparable interface? What is a comparator? How many comparisons are needed in the worst case to find the target value among 15 values using Sequential Search? Using Binary Search?

14-42 Review (cont’d): Describe briefly the main idea of Selection Sort. Describe briefly the main idea of Insertion Sort. Is it easier to implement Mergesort recursively or iteratively? What is the average number of comparisons in Mergesort? Name a few methods of the java.util.Arrays class.