Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Created March 3, 2017 02:07
Show Gist options
  • Select an option

  • Save drem-darios/26bbce49fe9e2cc27f3eb077d1b0b549 to your computer and use it in GitHub Desktop.

Select an option

Save drem-darios/26bbce49fe9e2cc27f3eb077d1b0b549 to your computer and use it in GitHub Desktop.
Merge Sort
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class MergeSort {
private static int[] result;
private static int[] temp;
private static int[] input = {45, 23, 11, 89, 77, 98, 4, 28, 65, 43};
public static void main(String[] args) {
result = input;
temp = new int[input.length];
doSplit(0, input.length - 1);
for (int i = 0; i < input.length; i++) {
System.out.println(result[i]);
}
}
private static void doSplit(int low, int high) {
int mid = low + (high - low)/2;
System.out.println(low + " " + mid + " " + high);
if (low < high) {
doSplit(low, mid);
System.out.println("&%");
doSplit(mid+1, high);
merge(low, mid, high);
}
System.out.println("Skipping "+low + " " + mid + " " + high);
}
private static void merge(int low, int mid, int high) {
System.out.println("** "+low + " " + mid + " " + high + " **");
// Populate temp array with values
for (int i = low; i <= high; i++) {
temp[i] = result[i];
}
int i = low;
int j = mid + 1;
int k = low; // current index for result
// loop while the lower end hasnt reached the mid
// and the higher end hasn't reached the end
while(i <= mid && j <= high) {
// check if lower end is smaller than higher end
if (temp[i] <= temp[j]) {
// if so, make current index take lower value
result[k] = temp[i];
i++;
} else {
// if not, take lower value from higher index
result[k] = temp[j];
j++;
}
// go to next index
k++;
}
// Loop while the lower end hasn't reached the mid point
while(i <= mid) {
// Copy over any that are left over
result[k] = temp[i];
k++;
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment