Merge Sort Hack 2
Here is my merge sort hack.
Option 1 - Adapt mergesort to other object
class Cookie {
private String name;
private int calories;
public Cookie(String name, int calories) {
this.name = name;
this.calories = calories;
}
public String getName() {
return name;
}
public int getCalories() {
return calories;
}
public String toString() {
return name + " - Calories: " + calories;
}
}
class CookieSort {
// Sorts in ascending order of calories
void merge(Cookie arr[], int l, int m, int r)
{
// Find the sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
Cookie[] L = new Cookie[n1];
Cookie[] R = new Cookie[n2];
/* Copy data to temp arrays */
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarray array
int k = l;
while (i < n1 && j < n2) {
// Uses the getCalories() method call to the Cookie Class
if (L[i].getCalories() <= R[j].getCalories()) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(Cookie arr[], int l, int r)
{
if (l < r) {
int m = l + (r - l) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
/* A utility function to print array of size n */
static void printArray(Cookie arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.println(arr[i]);
System.out.println();
}
// Tester method
public static void main(String args[])
{
// Initializes an array of Cookie objects
Cookie[] arr = {
new Cookie("Chocolate Chip", 150),
new Cookie("Oatmeal Raisin", 120),
new Cookie("Sugar Cookie", 90),
new Cookie("Peanut Butter", 200),
};
System.out.println("Given Array");
printArray(arr);
CookieSort ob = new CookieSort();
ob.sort(arr, 0, arr.length - 1);
System.out.println();
System.out.println("Sorted array");
printArray(arr);
}
}
CookieSort.main(null);