Created
September 5, 2018 14:05
-
-
Save sravanthi17/7b52a874f2e58d18e5da72bf259d76e9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package com.company; | |
import java.util.Scanner; | |
public class MergeSort { | |
public static void main(String[] args) { | |
// write your code here | |
System.out.println("Please enter the size of array"); | |
Scanner scanner = new Scanner(System.in); | |
int size = scanner.nextInt(); | |
int[] input = new int[size+1]; | |
int i =1; | |
System.out.println("Please enter elements in an array"); | |
while(i <= size){ | |
input[i]= scanner.nextInt(); | |
i++; | |
} | |
mergeSort(size, input); | |
System.out.println("----Sorted array-----"); | |
for (int j = 1; j <= size; j++) { | |
System.out.println(input[j]); | |
} | |
} | |
public static void mergeSort(int n, int[] inputArray){ | |
if(n > 1){ | |
int h = n/2; | |
int m = n-h; | |
int[] U = new int[n]; | |
int[] V = new int[n]; | |
for (int i = 1; i <= h; i++) { | |
U[i] = inputArray[i]; | |
} | |
int k=1; | |
for (int i = h+1; i <= n; i++) { | |
V[k] = inputArray[i]; | |
k++; | |
} | |
mergeSort(h, U); | |
mergeSort(m, V); | |
merge(h, m, U, V, inputArray); | |
} | |
} | |
public static void merge(int h, int m, int[] U, int[] V, int[] inputArray){ | |
int i=1, j=1, k=1, sourcePointer, destinationPointer; | |
while (i <= h && j <= m) { | |
if ( U[i] < V[j]) { | |
inputArray[k] = U[i]; | |
i++; | |
} | |
else { | |
inputArray[k] = V[j]; | |
j++; | |
} | |
k++; | |
} | |
if (i > h){ | |
sourcePointer = j; | |
destinationPointer= k; | |
while(sourcePointer <= m && destinationPointer <= h+m){ | |
inputArray[destinationPointer] = V[sourcePointer]; | |
sourcePointer++; | |
destinationPointer++; | |
} | |
} | |
else | |
{ | |
sourcePointer = i; | |
destinationPointer= k; | |
while(sourcePointer <= h && destinationPointer <= h+m){ | |
inputArray[destinationPointer] = U[sourcePointer]; | |
sourcePointer++; | |
destinationPointer++; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment