Presentation is loading. Please wait.

Presentation is loading. Please wait.

Comparing Objects in Java

Similar presentations


Presentation on theme: "Comparing Objects in Java"— Presentation transcript:

1 Comparing Objects in Java
boolean result = obj1.equals(obj2); int diff = obj1.compareTo(obj2); int diff = c.compare(obj1, obj2); Comparators and compare are not in the AP subset.

2 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. String also has equalsIgnoreCase.

3 obj1.compareTo(obj2) compareTo is an abstract method defined in the java.util.Comparable<T> 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); T is the type parameter Comparable is a generic interface: the type is a parameter. Sort of like obj1 - obj2

4 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. Comparable objects are also used in TreeSet, TreeMap, and PriorityQueue (Chapter 20).

5 obj1.compareTo(obj2) (cont’d)
«interface» Comparable<String> «interface» Comparable<Integer> «interface» Comparable<Double> String Integer Double compareTo is based on lexicographical order compareTo is based on numerical values A string that starts with a capital letter is smaller than a string that starts with a lowercase letter, because uppercase letters come before lowercase letters in ASCII and Unicode.

6 Sequential Search Scans the list comparing the target value to each element. Dan Fay 1 Cal 2 Ben 3 Guy 4 Amy 5 Eve 6 Amy? Amy? Amy? Amy? Amy? Amy! Sequential search also works for a linked list (see Chapter 21).

7 Sequential Search (cont’d)
public int sequentialSearch(Object [ ] arr, Object target) { for (int i = 0; i < arr.length ; i++) if (target.equals(arr [i])) return i; } return -1; This method returns the position of the target value, similar to indexOf in ArrayList. For primitive data types it is if (value == arr [ i ])

8 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. The average number of comparisons only makes sense if we always choose one of the elements randomly as a target. If the target-not-found situation is allowed, and we don’t know how often it happens, we can’t talk about the average. Also the average doesn’t make sense if the target is more often equal to, say, one of the first elements.

9 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). There is also a way to represent a list as a linked list (Chapter 21). Binary Search doesn’t work for a linked list.

10 Binary Search (cont’d)
Amy Ben 1 Cal 2 Dan 3 Eve 4 Fay 5 Guy 6 Eve? Amy Ben 1 Cal 2 Dan 3 Eve 4 Fay 5 Guy 6 Eve? Algorithms of this kind are called “divide-and-conquer” algorithms. Amy Ben 1 Cal 2 Dan 3 Eve 4 Fay 5 Guy 6 Eve!

11 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); } The base cases are when right < left and when the target value is found right away.

12 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 The while loop always terminates, because the difference right - left is always decreased at least by 1.

13 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. log n and log2 n differ by a constant factor, so it doesn’t matter which one to use.

14 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 For example if you want to merge two mailing lists into one eliminating the duplicates, it is more efficient to sort each list first.

15 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, n2 by the “order of magnitude.”) Faster “divide and conquer” sorting algorithms need approximately n·log2 n comparisons (much better). What kind of tricks? Well suppose we know that the list contains only values 0 through 9. We can scan the list once and count the number of times each value occurs, then generate a new list with the appropriate number of 0s, 1s, etc.

16 Sorting (cont’d) n2 n log2 n n Time n 10 100 1000
When n is large enough, An2 eventually overtakes Bn log n no matter how small A is and how large B is. n n n , ,000,000 n log2 n ,000

17 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) 1 13 8 5 2 1 3 n 1 3 8 5 2 1 13 n Or you can select the smallest value and swap it with the first element. 1 3 8 5 2 1 13 n

18 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--; } There is a simple recursive implementation, too. swap a[maxPos] and a[n-1]

19 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(n2) algorithm. Selection Sort is too slow for large arrays.

20 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) 2 1 3 5 13 1 8 Here we search for the place to insert the value starting from the k-th element backward, not from the beginning. This works better when the array is already sorted. k 1 2 3 5 13 1 8 k

21 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 It can be programmed recursively, too.

22 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(n2) algorithm. The number of moves may be greater than in Selection Sort. Insertion Sort is good when the array is almost sorted with only a few elements out of place.

23 The smaller value goes first
Mergesort 1. Split the array into two roughly equal “halves.” 2. Sort (recursively) each half using... Mergesort. 3. Merge the two sorted halves together. 5 1 3 2 4 7 6 1 3 5 2 4 6 7 Another divide-and-conquer algorithm. All the work actually happens at the merging phase. 1 3 5 1 2 3 2 4 6 7 The smaller value goes first

24 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); } Base case Optional shortcut: “if not yet sorted”... Both copy and merge are private helper methods. Mergesort needs a temporary array, but it is not a good idea to allocate a large array in a recursive method because it will be allocated at each level of recursion, which may take too much space. Luckily, in this algorithm we can reuse the same temporary array at all levels of recursive calls. For example, we can make temp a private static field in the Mergesort class. double[ ] temp is initialized outside the mergesort method

25 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. The suggested shortcut is not a canonical “textbook” feature. It’s just an example of how a minor change can dramatically improve a recursive algorithm.

26 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. 5 1 6 2 4 7 3 Any element can be chosen as a pivot. For example, we can choose the middle element, or we can take any three elements and choose the median. Quicksort is not in the AP subset. 4 1 3 2 5 7 6

27 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. If the array is already sorted, and we always choose the first element (of the segment that is being sorted) as pivot, then Quicksort degenerates into a slow version of Selection Sort.

28 The Benchmarks program
Enter the array size Choose the sorting algorithm This program fills an array with random numbers, then sorts it and measures how long it took. Running time in milliseconds

29 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. the seed is different each time Random generator1 = new Random( ); Random generator2 = new Random(seed); In this program we want to be “fair” and run each sorting algorithm on the same set of “random” data. We use the java.util.Random class, which allows us to generate the same “random” sequence several times. long seed;

30 java.util.Random (cont’d)
Methods: int k = generator.nextInt (n); double x = generator.nextDouble ( ); 0  k < n 0  x < 1 nextInt produces all 232 possible int values with approximately equal probability.

31 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); Needs import java.util.Arrays; All methods in Arrays are static; you cannot instantiate this class. The Arrays class is not in the AP subset. Returns a representation of arr as a fixed-length list

32 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); Needs import java.util.Collections; The Collections class is not in the AP subset.

33 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? What is the type of the parameter in the equals method? Object How many methods are listed in the Comparable interface? One: compareTo What is a comparator? An object that has a compare(X obj1, X obj2) method and is used to compare two objects of the class X. How many comparisons are needed in the worst case to find the target value among 15 values using Sequential Search? Using Binary Search? 15 and 4 (assuming the value might not be in the array).

34 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. Describe briefly the main idea of Selection Sort. Find the largest element; swap it with the last element; decrement the “logical” size of the array by one; repeat until the size of the array becomes 1. Describe briefly the main idea of Insertion Sort. Keep the first k elements in order (starting from k = 1); take the next element, insert in the right place among the first k and increment k; repeat until k becomes equal to the size of the array. Is it easier to implement Mergesort recursively or iteratively? Recursively What is the average number of comparisons in Mergesort? Roughly n log2 n Name a few methods of the java.util.Arrays class. binarySearch, sort, fill, toString(arr), asList(arr)


Download ppt "Comparing Objects in Java"

Similar presentations


Ads by Google