- Joined
- Mar 24, 2009
- Messages
- 173
- Reaction score
- 18
PHP:
class MergeSort {
private int[] a;
public MergeSort(int[] array) {
this.a = array;
ms(0, a.length-1);
System.out.print("MergeSort: [" + a[0]);
for (int i = 1; i < a.length; i++) {
System.out.print(", " + a[i]);
}
System.out.println("]");
}
private void ms(int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
ms(low, mid);
ms(mid+1, high);
merge(low, mid, high);
}
}
private void merge (int low, int mid, int high) {
int[] b = new int[a.length];
int i, j, k;
for (i = low; i <= high; i++)
b[i]=a[i];
i = low; j = mid+1; k = low;
while (i <= mid && j <= high)
if (b[i]<=b[j])
a[k++]=b[i++];
else
a[k++]=b[j++];
while (i <= mid)
a[k++]=b[i++];
}
}
This runs with nlog
