initial commit

This commit is contained in:
Vaibhav Sahay 2018-09-29 15:22:22 +05:30 committed by GitHub
parent c98a0234ae
commit 191b27a8c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 50 additions and 0 deletions

View File

@ -0,0 +1,50 @@
package com.baeldung.algorithms.mergesort;
public class MergeSort {
public static void main(String[] args) {
int[] a = { 5, 1, 6, 2, 3, 4 };
mergeSort(a, a.length);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void mergeSort(int[] a, int n) {
if (n < 2)
return;
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] < r[j])
a[k++] = l[i++];
else
a[k++] = r[j++];
}
while (i < left)
a[k++] = l[i++];
while (j < right)
a[k++] = r[j++];
}
}