Skip to content

Commit bf906dd

Browse files
Added partial array reverse
1 parent ed86c63 commit bf906dd

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

src/main/java/algorithms/array/ReverseArray.java

+5-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@
33
public class ReverseArray {
44

55
public static int[] reverse(int[] arr) {
6-
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
6+
return reverse(arr, 0, arr.length);
7+
}
8+
9+
public static int[] reverse(int[] arr, int offset, int length) {
10+
for (int i = offset, j = offset + length - 1; i < j; i++, j--) {
711
int tmp = arr[i];
812
arr[i] = arr[j];
913
arr[j] = tmp;
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,27 @@
11
package algorithms.array
22

3+
import algorithms.array.ReverseArray._
34
import org.scalatest.{FlatSpec, Matchers}
45

56
class ReverseArraySpec extends FlatSpec with Matchers {
67

78
it should "reverse the whole array" in {
8-
//given
9-
val arr = Array(1, 2, 3, 4, 5)
10-
11-
//when
12-
val result = ReverseArray.reverse(arr)
13-
14-
//then
15-
result.toList shouldBe List(5, 4, 3, 2, 1)
9+
//when & then
10+
reverse(Array.empty[Int]).toList shouldBe Nil
11+
reverse(Array(1)).toList shouldBe List(1)
12+
reverse(Array(1, 2)).toList shouldBe List(2, 1)
13+
reverse(Array(1, 2, 3, 4, 5)).toList shouldBe List(5, 4, 3, 2, 1)
14+
}
15+
16+
it should "reverse part of the array" in {
17+
//when & then
18+
reverse(Array(1, 2, 3, 4, 5, 6, 7), 0, 0).toList shouldBe List(1, 2, 3, 4, 5, 6, 7)
19+
reverse(Array(1, 2, 3, 4, 5, 6, 7), 0, 1).toList shouldBe List(1, 2, 3, 4, 5, 6, 7)
20+
reverse(Array(1, 2, 3, 4, 5, 6, 7), 0, 2).toList shouldBe List(2, 1, 3, 4, 5, 6, 7)
21+
reverse(Array(1, 2, 3, 4, 5, 6, 7), 0, 3).toList shouldBe List(3, 2, 1, 4, 5, 6, 7)
22+
reverse(Array(1, 2, 3, 4, 5, 6, 7), 1, 2).toList shouldBe List(1, 3, 2, 4, 5, 6, 7)
23+
reverse(Array(1, 2, 3, 4, 5, 6, 7), 1, 4).toList shouldBe List(1, 5, 4, 3, 2, 6, 7)
24+
reverse(Array(1, 2, 3, 4, 5, 6, 7), 5, 2).toList shouldBe List(1, 2, 3, 4, 5, 7, 6)
25+
reverse(Array(1, 2, 3, 4, 5, 6, 7), 6, 0).toList shouldBe List(1, 2, 3, 4, 5, 6, 7)
1626
}
1727
}

0 commit comments

Comments
 (0)