Merge pull request #5345 from vaibs28/master

BAEL-2211 Merge Sort
This commit is contained in:
Loredana Crusoveanu 2018-09-29 15:39:01 +03:00 committed by GitHub
commit 7d7eea291c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 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++];
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.mergesort;
import org.junit.Assert;
import org.junit.Test;
public class MergeSortUnitTest {
@Test
public void positiveTest() {
int[] actual = { 5, 1, 6, 2, 3, 4 };
int[] expected = { 1, 2, 3, 4, 5, 6 };
MergeSort.mergeSort(actual, actual.length);
Assert.assertArrayEquals(expected, actual);
}
}