Skip to content

Instantly share code, notes, and snippets.

@earthling-shruti
Created March 26, 2013 02:21
Show Gist options
  • Save earthling-shruti/5242615 to your computer and use it in GitHub Desktop.
Save earthling-shruti/5242615 to your computer and use it in GitHub Desktop.
public void mergeSort(int initial[], int start, int end){
if(start < end){
int mid = (start + end) / 2;
mergeSort(initial, start, mid);
mergeSort(initial, mid+1, end);
merge(initial, start, mid, end);
}
}
public int[] merge(int initial[], int start, int mid, int end){
int helper[] = new int[initial.length];
int left = start;
int right = mid + 1;
int current = left;
for(int i=start; i<end; i++){
helper[i] = initial[i];
}
while(left <= mid && right <=end){
//merge until one list is empty
if(helper[left] < helper[right]){
initial[current] = helper[left]; left++;
}
else{ initial[current] = helper[right]; right++;}
current++;
}
//one list is over, enter the remaining numbers from the other list
if(left == mid){while(right <= end){initial[right] = helper[right]; right++;}}
else if(right == end) {while(left <= mid){initial[left] = helper[left]; left++;}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment