File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package br.com.zevolution.algorithms.sorting.mergesort;
2+
3+
import java.util.Arrays;
4+
5+
public class MergeSort {
6+
7+
public static void main(String[] args) {
8+
9+
// Two previously ordered parts
10+
Product[] products = {
11+
new Product("product2", 4),
12+
new Product("product3", 5),
13+
new Product("product5", 8),
14+
new Product("product6", 9),
15+
new Product("product1", 3),
16+
new Product("product4", 6),
17+
new Product("product7", 9.3),
18+
new Product("product8", 10)
19+
};
20+
21+
Product[] array = sort(products);
22+
23+
24+
System.out.println(Arrays.toString(array));
25+
26+
}
27+
28+
private static Product[] sort(Product[] products) {
29+
int medium = products.length / 2;
30+
Product[] array = new Product[products.length];
31+
32+
int current = 0;
33+
int left = 0;
34+
int right = medium;
35+
36+
while (left < medium && right < products.length) {
37+
if (products[left].getPrice() < products[right].getPrice()) {
38+
array[current] = products[left];
39+
left++;
40+
} else {
41+
array[current] = products[right];
42+
right++;
43+
}
44+
current++;
45+
}
46+
47+
return array;
48+
}
49+
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package br.com.zevolution.algorithms.sorting.mergesort;
2+
3+
public class Product {
4+
5+
private String description;
6+
private double price;
7+
8+
public Product(String description, double price) {
9+
this.description = description;
10+
this.price = price;
11+
}
12+
13+
public double getPrice() {
14+
return price;
15+
}
16+
17+
@Override
18+
public String toString() {
19+
return this.description;
20+
}
21+
22+
}

0 commit comments

Comments
 (0)