Skip to content

Commit e9729e5

Browse files
committed
Adjusted method to sort a totally unsorted array
1 parent e13f520 commit e9729e5

File tree

1 file changed

+33
-15
lines changed
  • src/main/java/br/com/zevolution/algorithms/sorting/mergesort

1 file changed

+33
-15
lines changed

src/main/java/br/com/zevolution/algorithms/sorting/mergesort/MergeSort.java

+33-15
Original file line numberDiff line numberDiff line change
@@ -6,34 +6,37 @@ public class MergeSort {
66

77
public static void main(String[] args) {
88

9-
// Two previously ordered parts
9+
// Unsorted array
1010
Product[] products = {
11-
new Product("product2", 4),
1211
new Product("product3", 5),
13-
new Product("product5", 8),
12+
new Product("product2", 4),
1413
new Product("product6", 9),
15-
new Product("product1", 3),
14+
new Product("product5", 8),
1615
new Product("product4", 6),
17-
new Product("product7", 9.3),
18-
new Product("product8", 10)
16+
new Product("product1", 3),
17+
new Product("product8", 10),
18+
new Product("product7", 9.3)
1919
};
2020

21-
Product[] array = sort(products);
21+
mergeSort(products, 0, 1, 2);
22+
mergeSort(products, 2, 3, 4);
23+
mergeSort(products, 4, 5, 6);
24+
mergeSort(products, 6, 7, 8);
25+
mergeSort(products, 0, 4, 8);
26+
// array = mergeSort(array, 0, 2, 4);
2227

23-
24-
System.out.println(Arrays.toString(array));
28+
System.out.println(Arrays.toString(products));
2529

2630
}
2731

28-
private static Product[] sort(Product[] products) {
29-
int medium = products.length / 2;
30-
Product[] array = new Product[products.length];
32+
private static void mergeSort(Product[] products, int low, int medium, int high) {
33+
Product[] array = new Product[high-low];
3134

3235
int current = 0;
33-
int left = 0;
36+
int left = low;
3437
int right = medium;
3538

36-
while (left < medium && right < products.length) {
39+
while (left < medium && right < high) {
3740
if (products[left].getPrice() < products[right].getPrice()) {
3841
array[current] = products[left];
3942
left++;
@@ -44,7 +47,22 @@ private static Product[] sort(Product[] products) {
4447
current++;
4548
}
4649

47-
return array;
50+
while (left < medium) {
51+
array[current] = products[left];
52+
left++;
53+
current++;
54+
}
55+
56+
while (right < high) {
57+
array[current] = products[right];
58+
right++;
59+
current++;
60+
}
61+
62+
for (int i = 0; i < current; i++ ) {
63+
products[low + i] = array[i];
64+
}
65+
4866
}
4967

5068
}

0 commit comments

Comments
 (0)