Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save graphoarty/a8e21364682a8419819b0f6946f645e0 to your computer and use it in GitHub Desktop.
Save graphoarty/a8e21364682a8419819b0f6946f645e0 to your computer and use it in GitHub Desktop.
public class MergeSortTest {
public static final int max = 10;
public static void main(String[] args){
int[] toSortArray = new int[max];
//Required variables:
//End - Required Variables
for(int i = 0; i < max; i++){
toSortArray[i] = (int) (Math.random()*100);
}
System.out.println("The array to be sorted is:");
for(int i = 0; i < max; i++){
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
//Beginning of the algorithm
mergeSortHelper(toSortArray,0,max-1);
// End of the algorithm
System.out.println("The sorted array is: ");
for(int i = 0; i < max; i++){
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
}
private static void mergeSortHelper(int[] toSortArray, int first, int last) {
partition(toSortArray, first, last);
}
private static void partition(int[] toSortArray, int first, int last) {
int mid = (first+last)/2;
if(first<last){
partition(toSortArray,first,mid);
partition(toSortArray,mid+1,last);
merge(toSortArray,first,mid,last);
}
}
private static void merge(int[] toSortArray, int first, int mid, int last) {
int[] newArray = new int[max];
int i, j, k;
i = first;
j = mid + 1;
k = 0;
while(i <= mid && j <= last){
if(toSortArray[i] < toSortArray[j]){
newArray[k] = toSortArray[i];
i++;
k++;
}else{
newArray[k] = toSortArray[j];
j++;
k++;
}
}
while(i <= mid){
newArray[k] = toSortArray[i];
i++;
k++;
}
while(j <= last){
newArray[k] = toSortArray[j];
j++;
k++;
}
for(i = first, j = 0; i <= last ; i++,j++){
toSortArray[i] = newArray[j];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment