class MergeSort {
public static void sort(int[] array) {
// auxilary array of size O(n) used by merge process
int[] aux = new int[array.length];
/////////////////////////////////
// Improvement 3 : Initialize aux only once
for(int i = 0; i < array.length; i++) {
aux[i] = array[i];
}
//////////////////////////////
sort(aux, array, 0, array.length-1);
}
private static void sort(int[] array, int[] aux, int low, int high) {
if(high <= low) {
return; // sorting not required
}
int mid = low + (high-low)/2;
/////////////////////////
// Improvement 3 : switch role of aux and array in each sort call
sort(aux, array, low, mid);
sort(aux, array, mid+1, high);
////////////////////////////
merge(array, aux, low, mid, high);
}
private static void merge(int[] array, int[] aux, int low, int mid, int high) {
///////////////////////////
// Removed initialize aux from here
//////////////////////////
// Improvement 3 :: merge array to aux
int 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) {
aux[k++] = array[j++];
} else if(j > high) {
aux[k++] = array[i++];
} else if(less(array[j], array[i])) {
aux[k++] = array[j++];
} else {
aux[k++] = array[i++];
}
}
}
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,15,2,4,6,0,20,22,5,10,3,1};
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 15 2 4 6 0 20 22 5 10 3
Sorted array :
0 2 3 4 5 6 7 9 10 11 12 13 15 16 20 22 24
Comments
Post a Comment