Last active
August 29, 2015 14:09
-
-
Save prasadwrites/1ed4c81c8a0784668778 to your computer and use it in GitHub Desktop.
Merge Sort algorithm in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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