1+ package section15_InterfaceAndGenerics ;
2+
3+ import java .util .Comparator ;
4+
5+ public class BubbleSortComparator {
6+
7+ public static void main (String [] args ) {
8+
9+ Car2 [] cars = new Car2 [5 ];
10+
11+ cars [0 ] = new Car2 (58 , 100 , "red" );
12+ cars [1 ] = new Car2 (45 , 20 , "blue" );
13+ cars [2 ] = new Car2 (70 , 3000 , "black" );
14+ cars [3 ] = new Car2 (90 , 60 , "green" );
15+ cars [4 ] = new Car2 (80 , 3600 , "yellow" );
16+
17+ bubbleSort (cars , new carSpeedComparator ());
18+ display (cars );
19+
20+ bubbleSort (cars , new carPriceComparator ());
21+ display (cars );
22+
23+ bubbleSort (cars , new carColorComparator ());
24+ display (cars );
25+ }
26+
27+ public static <T > void display (T [] arr ) {
28+ for (T val : arr )
29+ System .out .println (val + " " );
30+ System .out .println ();
31+ }
32+
33+ // O(N^2) Time | O(1) Space
34+ public static <T > void bubbleSort (T [] arr , Comparator <T > comparator ) {
35+ for (int pass = 0 ; pass < arr .length - 1 ; pass ++) {
36+
37+ for (int j = 0 ; j < arr .length - 1 - pass ; j ++) {
38+
39+ if (comparator .compare (arr [j ], arr [j + 1 ]) > 0 ) {
40+
41+ T temp = arr [j ];
42+ arr [j ] = arr [j + 1 ];
43+ arr [j + 1 ] = temp ;
44+ }
45+ }
46+ }
47+ }
48+
49+ }
50+
51+ /* output:
52+
53+ Speed: 45 Price: 20 Color: blue
54+ Speed: 58 Price: 100 Color: red
55+ Speed: 70 Price: 3000 Color: black
56+ Speed: 80 Price: 3600 Color: yellow
57+ Speed: 90 Price: 60 Color: green
58+
59+ Speed: 80 Price: 3600 Color: yellow
60+ Speed: 70 Price: 3000 Color: black
61+ Speed: 58 Price: 100 Color: red
62+ Speed: 90 Price: 60 Color: green
63+ Speed: 45 Price: 20 Color: blue
64+
65+ Speed: 70 Price: 3000 Color: black
66+ Speed: 45 Price: 20 Color: blue
67+ Speed: 90 Price: 60 Color: green
68+ Speed: 58 Price: 100 Color: red
69+ Speed: 80 Price: 3600 Color: yellow
70+
71+ */
0 commit comments