diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java new file mode 100644 index 0000000000..5ba225cead --- /dev/null +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java @@ -0,0 +1,25 @@ +package com.baeldung.algorithms.inoutsort; + +public class InOutSort { + + public static int[] reverseInPlace(int A[]) { + int n = A.length; + for (int i = 0; i < n / 2; i++) { + int temp = A[i]; + A[i] = A[n - 1 - i]; + A[n - 1 - i] = temp; + } + + return A; + } + + public static int[] reverseOutOfPlace(int A[]) { + int n = A.length; + int[] B = new int[n]; + for (int i = 0; i < n; i++) { + B[n - i - 1] = A[i]; + } + + return B; + } +} diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java new file mode 100644 index 0000000000..321b905f68 --- /dev/null +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.algorithms.inoutsort; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; + +import org.junit.Test; + +public class InOutSortUnitTest { + + @Test + public void givenArray_whenInPlaceSort_thenReversed() { + int[] input = {1, 2, 3, 4, 5, 6, 7}; + int[] expected = {7, 6, 5, 4, 3, 2, 1}; + assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseInPlace(input)); + } + + @Test + public void givenArray_whenOutOfPlaceSort_thenReversed() { + int[] input = {1, 2, 3, 4, 5, 6, 7}; + int[] expected = {7, 6, 5, 4, 3, 2, 1}; + assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseOutOfPlace(input)); + } +}