1
1
package br .com .zevolution .algorithms .sorting .quicksort ;
2
2
3
+ import java .util .Arrays ;
4
+
3
5
import br .com .zevolution .algorithms .sorting .Product ;
4
6
5
7
public class QuickSort {
@@ -14,22 +16,34 @@ public static void main(String[] args) {
14
16
new Product ("Notebook" , 3500 )
15
17
};
16
18
17
- getCheapests (products , products .length );
19
+ int cheapests = getCheapests (products , products .length );
20
+ System .out .println (String .format ("There are %d cheaper products." , cheapests ));
18
21
22
+ System .out .println (Arrays .toString (products ));
19
23
}
20
24
21
- private static void getCheapests (Product [] products , int length ) {
25
+ private static int getCheapests (Product [] products , int length ) {
22
26
int cheapest = 0 ;
23
27
28
+ Product pivotProduct = products [length - 1 ];
24
29
for (int current = 0 ; current < length - 1 ; current ++) {
25
30
Product currentProduct = products [current ];
26
- if (currentProduct .getPrice () < products [length - 1 ].getPrice ()) {
31
+ if (currentProduct .getPrice () < pivotProduct .getPrice ()) {
32
+ swap (products , current , cheapest );
27
33
cheapest ++;
28
34
}
29
35
}
30
36
31
- System . out . println ( String . format ( "There are %d cheaper products." , cheapest ) );
37
+ swap ( products , length - 1 , cheapest );
32
38
39
+ return cheapest ;
40
+ }
41
+
42
+ private static void swap (Product [] products , int from , int to ) {
43
+ Product productFrom = products [from ];
44
+ Product productTo = products [to ];
45
+ products [from ] = productTo ;
46
+ products [to ] = productFrom ;
33
47
}
34
48
35
49
}
0 commit comments