Java Methods ObjectOriented Programming and Data Structures 2
Java Methods Object-Oriented Programming and Data Structures 2 nd AP edition with Grid. World Maria Litvin ● Gary Litvin 14 ACEHRPT Searching and Sorting Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. 1
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 2
Comparing Objects in Java • boolean result = obj 1. equals(obj 2); • int diff = obj 1. compare. To(obj 2); • int diff = c. compare(obj 1, obj 2); 3
obj 1. equals(obj 2) • 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 4
obj 1. equals(obj 2) (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 5
obj 1. equals(obj 2) (cont’d) • equals is called polymorphically from library methods, such as Array. List’s contains or index. Of that is why we have to properly override Object’s equals. • The equals method is properly defined in String, Integer, Double, etc. 6
obj 1. compare. To(obj 2) • compare. To is an abstract method defined in the java. util. Comparable<T> interface: public int compare. To (T other); • Returns a positive integer if obj 1 is T is the type parameter “greater than” obj 2, a negative integer if obj 1 is “less than” obj 2, zero if they are “equal. ” Sort of like obj 1 - obj 2 7
obj 1. compare. To(obj 2) (cont’d) public class Pet implements Comparable<Pet> { private String name; . . . public int compare. To(Pet other) { return name. compare. To(other. name); } public boolean equals(Object other) { return other instanceof Pet && compare. To((Pet)other) == 0; } equals is not required by Comparable, but it is a good idea to provide it and make it agree with compare. To } 8
obj 1. compare. To(obj 2) (cont’d) • compare. To is called polymorphically from library methods, such as Arrays. binary. Search(Object[ ] arr). • Objects of classes that implement Comparable are called “comparable” (pronounced com-'parable). • Strings, Integers, Doubles are comparable. 9
obj 1. compare. To(obj 2) (cont’d) «interface» Comparable<St ring> «interface» Comparable<In teger> «interface» Comparable<Do uble> String Integer Double compare. To is based on lexicographical order compare. To is based on numerical values 10
compare(obj 1, obj 2) • compare is an abstract method defined in the java. util. Comparator<T> interface: public int compare (T obj 1, T obj 2); T is the type parameter • Returns a positive integer if obj 1 is “greater than” obj 2, a negative integer if obj 1 is “less than” obj 2, zero if they are “equal. ” Sort of like obj 1 - obj 2 11
compare (obj 1, obj 2) (cont’d) public class Pet. Comparator. By. Name implements Comparator<Pet> {. . . public int compare (Pet pet 1, Pet pet 2) { return pet 1. get. Name(). compare. To(pet 2. get. Name()); } } 12
compare(obj 1, obj 2) (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<T> c) (or from your own methods) that take a comparator object as a parameter. 13
Sequential Search • Scans the list comparing the target value to each element. Dan 0 Fay 1 Cal 2 Ben 3 Guy 4 Amy 5 Amy? Amy? Amy! Eve 6 14
Sequential Search (cont’d) public int sequential. Search(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 ]) 15
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. 16
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 Array. List are OK). 17
Binary Search (cont’d) Amy 0 Ben 1 Cal 2 Dan 3 Eve 4 Fay 5 Guy 6 Eve? Amy 0 Ben 1 Cal 2 Dan 3 Eve 4 Fay 5 Guy 6 Eve! 18
Binary Search (cont’d) • Recursive implementation: public int binary. Search (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 binary. Search (arr, value, left, middle - 1); else // if ( value > arr[middle]) return binary. Search (arr, value, middle + 1, right); } 19
Binary Search (cont’d) • Iterative implementation: public int binary. Search (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 } 20
Binary Search (cont’d) • A “divide and conquer” algorithm. • Works very fast: only 20 comparisons are needed for an array of 1, 000 elements; (30 comparisons can handle 1, 000, 000 elements; etc. ). • We say that this is an O(log n) algorithm. 21
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 22
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). 23
Sorting (cont’d) Time n 2 n log 2 n 10 100 35 100 10, 000 700 1000 1, 000 10, 000 24
Selection Sort 1. Select the max among the first n elements: 1 13 8 5 2 1 3 n 2. Swap it with the n-th element : 1 3 8 5 2 1 13 n 3. Decrement n by 1 and repeat from Step 1 (while n > 1) 1 3 8 5 n 2 1 13 25
Selection Sort (cont’d) • Iterative implementation: public void selection. Sort (double [ ] arr, int n) { while (n > 1) { int max. Pos = 0; for (int k = 1; k < n; k++) if (arr [k] > arr [max. Pos] ) max. Pos = k; double temp = arr [max. Pos]; swap a[max. Pos] arr [max. Pos] = arr [n-1]; and a[n-1] arr [n-1] = temp; n--; } } 26
Selection Sort (cont’d) • The total number of comparisons is always (n-1) + (n-2) +. . . + 1 = n(n-1) / 2 • No average, best, or worst case — always the same. • An O(n 2) algorithm. 27
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. 2 13 1 8 1 3 5 k 3. Increment k by 1; repeat from Step 2 (while k < n) 1 2 3 5 13 1 8 k 28
Insertion Sort (cont’d) • Iterative implementation: public void insertion. Sort (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 29
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. 30
Mergesort 1. Split the array into two roughly equal “halves. ” 5 1 3 2 4 7 6 2. Sort (recursively) each half using. . . Mergesort. 1 3 5 2 4 6 7 3. Merge the two sorted halves together. 1 3 1 2 3 2 4 5 6 7 The smaller value goes first 31
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”. . . double[ ] temp is initialized outside the mergesort method 32
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. 33
Quicksort 1. Pick one element, called “pivot” 5 1 6 2 4 7 3 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. 4 1 3 2 5 7 6 3. Sort recursively the left and the right segments using. . . Quicksort. 34
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. 35
The Benchmarks program Enter the array size Choose the sorting algorithm Running time in milliseconds 36
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 generator 1 = new Random(); Random generator 2 = new Random(seed); long seed; • If we set the same seed, we get the same “random” sequence. 37
java. util. Random (cont’d) • Methods: int k = generator. next. Int (n); 0 �k < n double x = generator. next. Double (); 0 �x < 1 38
java. util. Arrays • Provides static methods for dealing with arrays. • Works for arrays of numbers, Strings, and Objects. • Methods: int pos = Arrays. binary. Search (arr, target); Arrays. sort (arr); Arrays. fill (arr, value); // fills arr with a given value String str = Arrays. to. String(arr); Arrays. as. List(arr); Returns a representation of arr as a fixed-length list 39
java. util. Collections • Provides static methods for dealing with Array. Lists and other Java collections. • Works for arrays of numbers, Strings, and Objects. • Methods: int pos = Collections. binary. Search (list, target); Collections. sort (list); Collections. shuffle (list); 40
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? 41
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. 42
- Slides: 42