class MergeSort {
public static void sort(int[] array) {
// auxilary array of size O(n) used by merge process
int[] aux = new int[array.length];
int N = array.length;
for (int sz = 1; sz < N; sz = 2*sz) {
for (int low = 0; low < N-sz; low = low + 2*sz) {
int high = Math.min(low + 2*sz-1, N-1);
int mid = low+sz-1;
merge(array, aux, low, mid, high);
}
}
}
private static void merge(int[] array, int[] aux, int low, int mid, int high) {
// copy from array to aux
int i = low;
for(; i <= high; i++) {
aux[i] = array[i];
}
// merge aux to array
i = low; // used for first sub array
int j = mid+1; // used for second sub array
int k = low; // used for merged array
while(k <= high) {
if(i > mid) {
array[k++] = aux[j++];
} else if(j > high) {
array[k++] = aux[i++];
} else if(less(aux[i], aux[j])) {
array[k++] = aux[i++];
} else {
array[k++] = aux[j++];
}
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static boolean less(int key1, int key2) {
return key1 < key2;
}
private static void display(int[] array) {
for(int key : array) {
System.out.print(key + " ");
}
}
public static void main (String[] args) {
int[] array = new int[] {11,13,7,12,16,9,24,5,10,3};
System.out.println("Unsorted array : ");
display(array);
sort(array);
System.out.println("\nSorted array : ");
display(array);
}
}
Unsorted array :
11 13 7 12 16 9 24 5 10 3
Sorted array :
3 5 7 9 10 11 12 13 16 24
Comments
Post a Comment