public class MergeSort {
private int[] numbers;
private int count;
public static void main(String[] args)
{
int[] a1 = new int[] { 3, 10, 5, 1, 9, 20, 11,8,15 };
MergeSort ms = new MergeSort(a1);
ms.mergesort(0, ms.count - 1);
for (int i : a1)
System.out.println(" " + i);
}
public MergeSort(int[] a)
{
numbers = a;
count = a.length;
}
private void mergesort(int low, int high) {
if (low < high) {
int middle = (low + high) / 2;
mergesort(low, middle);
mergesort(middle + 1, high);
merge(low, middle, high);
}
}
private void merge(int low, int middle, int high) {
int helper[] = new int[high+1];
for (int i = low; i <= high; i++) {
helper[i] = numbers[i];
}
int i = low;
int j = middle + 1;
int k = low;
while (i <= middle && j <= high) {
if (helper[i] <= helper[j]) {
numbers[k] = helper[i];
i++;
} else {
numbers[k] = helper[j];
j++;
}
k++;
}
while (i <= middle) {
numbers[k] = helper[i];
k++;
i++;
}
while (j <= high) {
numbers[k] = helper[j];
k++;
j++;
}
}
Comments
Post a Comment