Skip to content

Instantly share code, notes, and snippets.

@ArielSaldana
Created June 14, 2016 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArielSaldana/f68357e084d21c19211d223e41c34834 to your computer and use it in GitHub Desktop.
Save ArielSaldana/f68357e084d21c19211d223e41c34834 to your computer and use it in GitHub Desktop.
/**
* Created by Ariel on 6/14/2016.
*/
public class MergeSort {
public static void merge(int [] arr, int start, int mid, int end) {
// our two buckets to compare later
int low[] = new int[(mid-start)+1];
int high[] = new int[end-mid];
int index = start;
// Copy the first half to the low bucket
for ( int i = 0; index <= mid; i++, index++ ) {
low[i] = arr[index];
}
// Copy the second half to the high bucket
for ( int j = 0; index <= end; j++, index++ ) {
high[ j ] = arr[ index ];
}
// Compare low and high... and input the data into the original array in order
int i = 0,
j = 0;
index = start;
while ( i < low.length && j < high.length ) {
if ( low[ i ] < high[ j ] ) {
arr[ index ] = low[ i ];
i++;
}
else {
arr[ index ] = high[ j ];
j++;
}
index++;
}
// just copy the rest of the "empty bucket"
while ( i < low.length ) {
arr[ index ] = low[ i ];
i++;
index++;
}
while ( j < high.length ) {
arr[index] = high[j];
j++;
index++;
}
}
public static void sort ( int [] arr, int start, int end ) {
int mid = (int)Math.floor( ( start+end ) / 2);
if ( end > start ) {
sort( arr,start,mid );
sort( arr,mid+1,end );
merge( arr, start, mid, end );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment