Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a7909fa

Browse files
Created method to swap cheapest items to the left side and most expensive to the right side of the pivot
1 parent 585e970 commit a7909fa

File tree

1 file changed

+18
-4
lines changed
  • src/main/java/br/com/zevolution/algorithms/sorting/quicksort

1 file changed

+18
-4
lines changed

‎src/main/java/br/com/zevolution/algorithms/sorting/quicksort/QuickSort.java

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package br.com.zevolution.algorithms.sorting.quicksort;
22

3+
import java.util.Arrays;
4+
35
import br.com.zevolution.algorithms.sorting.Product;
46

57
public class QuickSort {
@@ -14,22 +16,34 @@ public static void main(String[] args) {
1416
new Product("Notebook", 3500)
1517
};
1618

17-
getCheapests(products, products.length);
19+
int cheapests = getCheapests(products, products.length);
20+
System.out.println(String.format("There are %d cheaper products.", cheapests));
1821

22+
System.out.println(Arrays.toString(products));
1923
}
2024

21-
private static void getCheapests(Product[] products, int length) {
25+
private static int getCheapests(Product[] products, int length) {
2226
int cheapest = 0;
2327

28+
Product pivotProduct = products[length - 1];
2429
for (int current = 0; current < length - 1; current++) {
2530
Product currentProduct = products[current];
26-
if (currentProduct.getPrice() < products[length - 1].getPrice()) {
31+
if (currentProduct.getPrice() < pivotProduct.getPrice()) {
32+
swap(products, current, cheapest);
2733
cheapest++;
2834
}
2935
}
3036

31-
System.out.println(String.format("There are %d cheaper products.", cheapest));
37+
swap(products, length - 1, cheapest);
3238

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;
3347
}
3448

3549
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /