Chapter 14 - Searching and sorting. This chapter is a survey of the basic searching and sorting algorithms including the four standard sorting algorithms. This chapter’s objectives are to: Learn about the three ways to compare objects in Java, learn the following algorithms.
Java Methods Object-Oriented Programming and Data Structures 2nd AP edition with GridWorld Maria Litvin ● Gary Litvin 14ACEHRPT Searching and Sorting Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing All rights reserved 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 142 Comparing Objects in Java • boolean result = obj1.equals(obj2); • int diff = obj1.compareTo(obj2); • int diff = c.compare(obj1, obj2); 143 obj1.equals(obj2) • The boolean method equals comes from the class Object: public boolean equals(Object other) { } • Object’s equals is not very useful: compares addresses of objects • Programmers often override equals in their classes 144 obj1.equals(obj2) (cont’d) public class Pet { Or: private String name; if (other instanceof Pet) public boolean equals (Object other) { if (other != null) return name.equals(((Pet)other).name); else instanceof return false; is a boolean } operator in } Java 145 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 146 obj1.compareTo(obj2) • compareTo is an abstract method defined in the java.util.Comparable interface: public int compareTo (T other); T is the type parameter • Returns a positive integer if obj1 is “greater than” obj2, a negative integer if obj1 is “less than” obj2, zero if they are “equal.” Sort of like obj1 - obj2 147 obj1.compareTo(obj2) (cont’d) public class Pet implements Comparable { equals is not private String name; required by Comparable, public int compareTo(Pet other) but it is a good { idea to provide return name.compareTo(other.name); it and make it } agree with compareTo public boolean equals(Object other) { return other instanceof Pet && compareTo((Pet)other) == 0; } } 148 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 149 obj1.compareTo(obj2) (cont’d) «interface» Comparable «interface» Comparable «interface» Comparable String Integer Double compareTo is based on lexicographical order compareTo is based on numerical values 1410 Insertion Sort k = 1; keep the first k elements in order Take the (k+1)-th element and insert among the first k in the right place 13 k Increment k by 1; repeat from Step (while k < n) 13 k 1428 Insertion Sort (cont’d) • Iterative implementation: public void insertionSort (double [ ] arr, int n) { for (int k = ; k < n; k++) { double temp = arr [ k ]; int i = k; while (i > && arr [i-1] > temp) { arr [i] = arr [i - 1]; i ; } arr [i] = temp; } } shift to the right 1429 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) / when the array is sorted in reverse order • On average, an O(n2) algorithm 1430 Mergesort Split the array into two roughly equal “halves.” Sort (recursively) each half using Mergesort Merge the two sorted halves together 3 The smaller value goes first 1431 Mergesort (cont’d) public void mergesort (double[ ] arr, int from, int to) { if (from arr [middle + 1]) { copy (arr, from, to, temp) ; merge (temp, from, middle, to, arr); } } Base case Optional shortcut: “if not yet sorted” double[ ] temp is initialized outside the mergesort method 1432 Mergesort (cont’d) • Takes roughly n·log2 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 1433 Quicksort Pick one element, called “pivot” 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 Sort recursively the left and the right segments using Quicksort 1434 Quicksort (cont’d) • Takes roughly n·log2 n comparisons • May get slow if pivot consistently fails to split the array into approximately equal halves • An O(n log n) algorithm 1435 The Benchmarks program Enter the array size Choose the sorting algorithm Running time in milliseconds 1436 java.util.Random • Benchmarks uses the java.util.Random class — a more controlled way to generate random numbers • Constructors: the seed is different each time Random generator1 = new Random(); Random generator2 = new Random(seed); long seed; • If we set the same seed, we get the same “random” sequence 1437 java.util.Random (cont’d) • Methods: int k = generator.nextInt (n); 0k