Skip to content

Instantly share code, notes, and snippets.

@mehtaparitosh
Created September 4, 2017 08:20
Show Gist options
  • Save mehtaparitosh/e13f2d59ee5e0bba7013a04b0caf609d to your computer and use it in GitHub Desktop.
Save mehtaparitosh/e13f2d59ee5e0bba7013a04b0caf609d to your computer and use it in GitHub Desktop.
package Sorting;
import java.util.*;
/**
*
* @author paritosh mehta
*/
public class MergeSort {
public static void merge(int[] left, int[] right, int[] arr){
int l, r, i=0, j=0, k=0;
//Declare length of left and right array
l = left.length;
r = right.length;
//Check both arrays, element by element
//and override in original array
while((i<l)&&(j<r)){
if(left[i]<=right[j]){
arr[k] = left[i];
k++;
i++;
}
else {
arr[k] = right[j];
k++;
j++;
}
}
//If right exhausts, pick remaining from left
while(i<l){
arr[k] = left[i];
k++;
i++;
}
//If left exhausts, pick remaining from right
while(j<l){
arr[k] = right[j];
k++;
j++;
}
}
public static void mergeSort(int[] arr){
//If the array of single value, return back
int n = arr.length;
if(n<2)
return;
//Find break point
int i, mid = n/2;
//Create left and right sub-arrays
int[] left = new int[mid];
int[] right = new int[n-mid];
//Store values in sub-arrays
//in left
for(i=0; i<mid; i++){
left[i] = arr[i];
}
//in right
for(i=0; i<n-mid; i++){
right[i] = arr[mid+i];
}
//Run recursive functions to sort left and right sub-array
mergeSort(left);
mergeSort(right);
//Merge both arrays together
merge(left, right, arr);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//Enter the size of array
System.out.print("Enter the size of the Array: ");
int n = sc.nextInt();
int[] arr = new int[n];
//Enter the array
int i;
System.out.println("Enter the Array: ");
for(i=0; i<n; i++){
System.out.print("A[" + (i+1) + "]: ");
arr[i] = sc.nextInt();
}
//Perform merge sort
mergeSort(arr);
//Print sorted array
System.out.println();
for(i=0; i<n; i++){
System.out.print("[" + arr[i] + "] ");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment