@@ -16,25 +16,33 @@ public static void main(String[] args) {
1616 new Product ("Notebook" , 3500 )
1717 };
1818
19- int cheapests = getCheapests (products , products .length );
20- System .out .println (String .format ("There are %d cheaper products." , cheapests ));
19+ quickSort (products , 0 , products .length );
2120
2221 System .out .println (Arrays .toString (products ));
2322 }
2423
25- private static int getCheapests (Product [] products , int length ) {
26- int cheapest = 0 ;
24+ private static void quickSort (Product [] products , int start , int end ) {
25+ int length = end - start ;
26+ if (length > 1 ) {
27+ int pivot = partitionProducts (products , start , end );
28+ quickSort (products , start , pivot );
29+ quickSort (products , pivot + 1 , end );
30+ }
31+ }
32+ 33+ private static int partitionProducts (Product [] products , int start , int end ) {
34+ int cheapest = start ;
2735
28- Product pivotProduct = products [length - 1 ];
29- for (int current = 0 ; current < length - 1 ; current ++) {
36+ Product pivotProduct = products [end - 1 ];
37+ for (int current = start ; current < end - 1 ; current ++) {
3038 Product currentProduct = products [current ];
31- if (currentProduct .getPrice () < pivotProduct .getPrice ()) {
39+ if (currentProduct .getPrice () <= pivotProduct .getPrice ()) {
3240 swap (products , current , cheapest );
3341 cheapest ++;
3442 }
3543 }
3644
37- swap (products , length - 1 , cheapest );
45+ swap (products , end - 1 , cheapest );
3846
3947 return cheapest ;
4048 }
0 commit comments