Skip to content

Instantly share code, notes, and snippets.

@prasadwrites
Last active August 29, 2015 14:09
Show Gist options
  • Save prasadwrites/1ed4c81c8a0784668778 to your computer and use it in GitHub Desktop.
Save prasadwrites/1ed4c81c8a0784668778 to your computer and use it in GitHub Desktop.
Merge Sort algorithm in Java
import java.io.*;
import java.util.*;
public class MergeSortAlgo{
static int arr[] = { 11,34,55,67,23,64,78,34,12,84,33,5,5};
private void MergeSort(int [] arr)
{
System.out.println("Split array " + Arrays.toString(arr));
if(arr.length > 1)
{
int [] leftpart;
int [] rightpart;
int mid = arr.length / 2;
if(arr.length%2 == 0)
{
leftpart = new int[mid];
rightpart = new int[mid];
System.arraycopy(arr, 0, leftpart, 0, mid);
System.arraycopy(arr, mid, rightpart, 0, mid);
}
else
{
leftpart = new int[mid+1];
rightpart = new int[mid];
System.arraycopy(arr, 0, leftpart, 0, mid+1);
System.arraycopy(arr, mid+1, rightpart, 0, mid);
}
MergeSort(leftpart);
MergeSort(rightpart);
int i=0,j=0,k=0;
while ((i<leftpart.length) && (j<rightpart.length))
{
if(leftpart[i] < rightpart[j])
{
arr[k] = leftpart[i];
i++;
}
else
{
arr[k] = rightpart[j];
j++;
}
k++;
}
while(i < leftpart.length)
{
arr[k] = leftpart[i];
i++;
k++;
}
while(j < rightpart.length)
{
arr[k] = rightpart[j];
j++;
k++;
}
}
System.out.println("Mergerd array " + Arrays.toString(arr));
}
public static void main(String []args)
{
System.out.println("Unsorted array " + Arrays.toString(arr));
MergeSortAlgo obj = new MergeSortAlgo();
obj.MergeSort(arr);
System.out.println("Sorted array " + Arrays.toString(arr));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment