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 7cf5ed7

Browse files
Implemented recursive algorithms concept in QuickSort
1 parent a7909fa commit 7cf5ed7

File tree

1 file changed

+16
-8
lines changed
  • src/main/java/br/com/zevolution/algorithms/sorting/quicksort

1 file changed

+16
-8
lines changed

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

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
(0)

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