
import java.security.SecureRandom;
import java.util.Comparator;
public class Exercise23_02 {
public static void main(String[] args) {
Integer[] list1 = new Integer[10];
for (int i = 0; i < list1.length; i++)
list1[i] = new SecureRandom().nextInt(20);
System.out.println(Arrays.toString(list1));
mergeSort(list1, new SortComparator<>());
System.out.println(Arrays.toString(list1));
String[] list2 = {"China", "Babylon", "Paris", "america", "India", "Japan"};
System.out.println(Arrays.toString(list2));
mergeSort(list2, new SortComparator<>());
System.out.println(Arrays.toString(list2));
Double[] list3 = new Double[10];
for (int i = 0; i < list3.length; i++)
list3[i] = Math.random() * 20;
System.out.println(Arrays.toString(list3));
mergeSort(list3, new SortComparator<>());
System.out.println(Arrays.toString(list3));
public static extends Comparable> void mergeSort(E[] list) {
E[] firstHalf = (E[])new Comparable[list.length / 2];
System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
int secondHalfLength = list.length - list.length / 2;
E[] secondHalf = (E[])new Comparable[secondHalfLength];
System.arraycopy(list, list.length / 2, secondHalf, 0, secondHalfLength);
merge(firstHalf, secondHalf, list);
private static extends Comparable> void merge(E[] list1, E[] list2, E[] temp) {
int current1, current2, current3;
current1 = current2 = current3 = 0;
while (current1 < list1.length && current2 < list2.length)
temp[current3++] = list1[current1].compareTo(list2[current2]) < 0 ? list1[current1++] : list2[current2++];
while (current1 < list1.length)
temp[current3++] = list1[current1++];
while (current2 < list2.length)
temp[current3++] = list2[current2++];
public static void mergeSort(E[] list, Comparator super E> comparator) {
E[] firstHalf = (E[])new Object[list.length / 2];
System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
mergeSort(firstHalf, comparator);
int secondHalfLength = list.length - list.length / 2;
E[] secondHalf = (E[])new Object[secondHalfLength];
System.arraycopy(list, list.length / 2, secondHalf, 0, secondHalfLength);
mergeSort(secondHalf, comparator);
merge(firstHalf, secondHalf, list, comparator);
private static void merge(E[] list1, E[] list2, E[] temp, Comparator super E> comparator) {
int current1, current2, current3;
current1 = current2 = current3 = 0;
while (current1 < list1.length && current2 < list2.length)
temp[current3++] = comparator.compare(list1[current1], list2[current2]) < 0 ? list1[current1++] : list2[current2++];
while (current1 < list1.length)
temp[current3++] = list1[current1++];
while (current2 < list2.length)
temp[current3++] = list2[current2++];
static class SortComparator implements Comparator {
public int compare(E o1, E o2) {
if (o1 instanceof Comparable) {
if (((Comparable) o1).compareTo(o2) > 0) return 1;
else if (((Comparable) o1).compareTo(o2) < 0) return -1;
if (o1.hashCode() > o2.hashCode())
else if (o1.hashCode() < o2.hashCode())

