-
Notifications
You must be signed in to change notification settings - Fork 1
/
Chapter 20
76 lines (64 loc) · 2.03 KB
/
Chapter 20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.*;
public class SortPoints {
public static void main(String[] args) {
Point[] points = new Point[100];
for (int i = 0; i < points.length; i++) {
points[i] = new Point(Math.random() * 100, Math.random() * 100);
}
System.out.println("Points sorted on x-coordinates: ");
Arrays.sort(points);
for (int i = 0; i < points.length; i++) {
System.out.println(points[i]);
}
System.out.println("\nPoints sorted on y-coordinates: ");
Arrays.sort(points, new CompareY()); //sort method is invoked to sort points using a comparator
for (int i = 0; i < points.length; i++) {
System.out.println(points[i]);
}
}
}
class Point implements Comparable<Point> {
double x;
double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point k) { //compares the x coordinates, k is short for key
if (x == k.x) { //if two points have the same x coordinate, compare their y coordinates
if (y > k.y) {
return 1;
} else if (y < k.y) {
return -1;
} else {
return 0;
}
} else if (x > k.x) {
return 1;
} else {
return -1;
}
}
public String toString() { //prints out the points in (x, y) format
return "(" + x + ", " + y + ")";
}
}
class CompareY implements Comparator<Point> { //compares two points on their y-coordinates
@Override
public int compare(Point k1, Point k2) { //comparator method
if (k1.y == k2.y) { //if two points have the same y coordinate, compare their x coordinates
if (k1.x > k2.x) {
return 1;
} else if (k1.x < k1.x) {
return -1;
} else {
return 0;
}
} else if (k1.y > k2.y) {
return 1;
} else {
return -1;
}
}
}