Python Program to Reverse an Array
Explanation
This program demonstrates how to reverse an array (or list) in Python. We will use a simple algorithm that swaps elements from the beginning of the array with elements from the end of the array. The process continues until we reach the middle of the array.
Code
# This Python program reverses an array.
# It demonstrates the basic concept of swapping elements in an array.
def reverse_array(array):
"""
This function reverses the given array in place.
It swaps elements from the beginning and end of the array until the middle is reached.
:param array: The array to be reversed.
"""
start = 0 # Starting index
end = len(array) - 1 # Ending index
# Loop until start index is less than end index
while start < end:
# Swap the elements at start and end
array[start], array[end] = array[end], array[start]
# Move the start index forward and end index backward
start += 1
end -= 1
def print_array(array):
"""
This function prints the elements of the given array.
:param array: The array whose elements are to be printed.
"""
print(" ".join(map(str, array)))
# Main function
if __name__ == "__main__":
# Initialize the array
array = [1, 2, 3, 4, 5]
# Print the original array
print("Original Array:")
print_array(array)
# Reverse the array
reverse_array(array)
# Print the reversed array
print("Reversed Array:")
print_array(array)
Explanation of the Code
Function Definitions:
The reverse_array
function contains the logic to reverse the array in place by swapping elements from the start and end. The print_array
function is used to print the elements of the array in a readable format.
Main Function:
The if __name__ == "__main__":
block serves as the entry point of the program. It initializes an array, prints the original array, calls the reverse_array
function to reverse the array, and then prints the reversed array.
reverse_array Function:
The reverse_array
function takes an array as input and reverses it in place. It uses two pointers: start
(initialized to the beginning of the array) and end
(initialized to the end of the array). The elements at these positions are swapped, and the pointers are moved towards the center. This process continues until the start index is less than the end index.
print_array Function:
The print_array
function takes an array as input and prints its elements. This is used to display the array before and after reversing it.