Write a method called swapSection that takes in 3 arguments in this order: an IntArray?, a start index
(Int), and an end index (also an Int). The problem "swaps" pairs of elements in a section of the array,
from the start index (inclusive) to the end index (also inclusive), and returns the swapped/modified array. If you
need to swap an odd number of elements, do not change the last element (only swap the pairs before it). Here are
some examples:
In the following examples, the swapped elements are in bold.
Example 1 (even length; entire array):
Array: [1, 2, 3, 4, 5, 6], startIndex: 0, endIndex: 5. Your method should return the array [2, 1, 4, 3, 6,
5]. Note how each pair is being reversed/swapped (e.g. [1, 2] turns into [2, 1]).
Example 2 (odd length; entire array):
Array: [1, 2, 3, 4, 5], startIndex: 0, endIndex: 4. Your method should return [2, 1, 4, 3, 5]. Note how
the last element is not being swapped, because it's not part of a pair.
Example 3 (even length; sub-array):
Array: [1, 2, 3, 4, 5, 6], startIndex: 1, endIndex: 4. Your method should return the array [1, 3, 2, 5,
4, 6]. In this case, only the sub-array (elements of index 1 through 4) are being swapped. Thus, we swap the
pairs only in that sub-array, and keep the rest of the array the same.
Example 4 (odd length; sub-array):
Array: [1, 2, 3, 4, 5, 6], startIndex: 1, endIndex: 3. Your method should return the array [1, 3, 2, 4,
5, 6]. Here, we are interested in indices 1, 2, and 3 (3 elements, an odd number), so we do NOT change the last
of the 3 elements (only the first pair).
Special Cases:
null! In this case, just return the original array (which is null) with no changes.Hints:
i and element i+1, because
you're swapping one pair at a time.Stuck? You may find these lessons helpful: