|
1 | 1 | package br.com.zevolution.algorithms.sorting.quicksort;
|
2 | 2 |
|
3 |
| -import java.util.Arrays; |
4 |
| - |
5 | 3 | import br.com.zevolution.algorithms.sorting.Product;
|
| 4 | +import br.com.zevolution.algorithms.sorting.Sort; |
| 5 | + |
| 6 | +public class QuickSort implements Sort { |
| 7 | + |
| 8 | +@Override |
| 9 | +public Product[] sort(Product[] products, int length) { |
| 10 | +Product[] array = products.clone(); |
| 11 | +this.quickSort(array, 0, length); |
| 12 | +return array; |
6 | 13 |
|
7 |
| -public class QuickSort { |
8 |
| - |
9 |
| -public static void main(String[] args) { |
10 |
| - |
11 |
| -Product[] products = { |
12 |
| -new Product("iMac", 30000), |
13 |
| -new Product("Keyboard", 100), |
14 |
| -new Product("iPhone 12 Pro Max Ultra Uou", 10000), |
15 |
| -new Product("Mouse", 50), |
16 |
| -new Product("Notebook", 3500) |
17 |
| -}; |
18 |
| - |
19 |
| -quickSort(products, 0, products.length); |
20 |
| - |
21 |
| -System.out.println(Arrays.toString(products)); |
22 | 14 | }
|
23 | 15 |
|
24 |
| -private static void quickSort(Product[] products, int start, int end) { |
| 16 | +private void quickSort(Product[] products, int start, int end) { |
25 | 17 | int length = end - start;
|
26 | 18 | if (length > 1) {
|
27 |
| -int pivot = partitionProducts(products, start, end); |
28 |
| -quickSort(products, start, pivot); |
29 |
| -quickSort(products, pivot + 1, end); |
| 19 | +int pivot = this.partitionProducts(products, start, end); |
| 20 | +this.quickSort(products, start, pivot); |
| 21 | +this.quickSort(products, pivot + 1, end); |
30 | 22 | }
|
31 | 23 | }
|
32 | 24 |
|
33 |
| -private static int partitionProducts(Product[] products, int start, int end) { |
| 25 | +private int partitionProducts(Product[] products, int start, int end) { |
34 | 26 | int cheapest = start;
|
35 |
| -
|
| 27 | + |
36 | 28 | Product pivotProduct = products[end - 1];
|
37 | 29 | for (int current = start; current < end - 1; current++) {
|
38 | 30 | Product currentProduct = products[current];
|
39 | 31 | if (currentProduct.getPrice() <= pivotProduct.getPrice()) {
|
40 |
| -swap(products, current, cheapest); |
| 32 | +this.swap(products, current, cheapest); |
41 | 33 | cheapest++;
|
42 | 34 | }
|
43 | 35 | }
|
44 |
| -
|
45 |
| -swap(products, end - 1, cheapest); |
46 |
| -
|
| 36 | + |
| 37 | +this.swap(products, end - 1, cheapest); |
| 38 | + |
47 | 39 | return cheapest;
|
48 | 40 | }
|
49 | 41 |
|
50 |
| -private static void swap(Product[] products, int from, int to) { |
| 42 | +private void swap(Product[] products, int from, int to) { |
51 | 43 | Product productFrom = products[from];
|
52 | 44 | Product productTo = products[to];
|
53 | 45 | products[from] = productTo;
|
54 | 46 | products[to] = productFrom;
|
55 | 47 | }
|
56 | 48 |
|
57 |
| -} |
| 49 | +} |
0 commit comments