1+ """
2+ In-place array reversal.
3+ This algorithm reverses the elements of a list without using extra space.
4+ """
5+
6+ from typing import Any
7+
8+
9+ def reverse_array (arr : list [Any ]) -> list [Any ]:
10+ """
11+ Reverses a list in-place.
12+
13+ This function takes a list and reverses its elements using a two-pointer
14+ approach. The left pointer starts at the beginning of the list, and the
15+ right pointer starts at the end. The elements at these two pointers are
16+ swapped, and the pointers move towards the center until they meet or cross.
17+
18+ Args:
19+ arr: The list to be reversed.
20+
21+ Returns:
22+ The same list, now reversed. This allows for method chaining.
23+
24+ Doctests:
25+ >>> reverse_array([1, 2, 3, 4, 5])
26+ [5, 4, 3, 2, 1]
27+ >>> reverse_array(['a', 'b', 'c', 'd'])
28+ ['d', 'c', 'b', 'a']
29+ >>> reverse_array([10.5, 20.2, 30.8])
30+ [30.8, 20.2, 10.5]
31+ >>> reverse_array(["apple", "banana", "cherry"])
32+ ['cherry', 'banana', 'apple']
33+ >>> reverse_array([1])
34+ [1]
35+ >>> reverse_array([])
36+ []
37+ """
38+ left = 0
39+ right = len (arr ) - 1
40+
41+ while left < right :
42+ # Swap the elements at the left and right pointers
43+ arr [left ], arr [right ] = arr [right ], arr [left ]
44+ # Move the pointers towards the center
45+ left += 1
46+ right -= 1
47+ return arr
48+
49+
50+ if __name__ == "__main__" :
51+ # The doctest module runs the tests embedded in the function's docstring.
52+ # To run the tests, execute this script from the command line:
53+ # python -m doctest -v reverse_array.py
54+ import doctest
55+
56+ doctest .testmod ()
57+
58+ # Example usage:
59+ print ("\n --- Example Usage ---" )
60+ sample_array = [10 , 20 , 30 , 40 , 50 , 60 ]
61+ print (f"Original array: { sample_array } " )
62+ reverse_array (sample_array )
63+ print (f"Reversed array: { sample_array } " )
0 commit comments