Python Program to Split the array and add the first part to the end
In this tutorial, we will learn how to split an array at a specified position and add the first part to the end. The user will specify the position from where the array has to be split and our program should move the first part of the array to the end of the array. Take look at the explanation given below,
Suppose there is an array[] with the elements [2, 3, 5, 12, 14, 27, 9] as follows
the user gives an input of p=3 which will specify the position from where the array has to be split,
The resultant array should be,
Take a look at the examples to understand the format of the input and the output
Input : a[] = {12, 10, 5, 6, 52, 36} p = 2
Output : a[] = {5, 6, 52, 36, 12, 10}
We will follow the approach of splitting the array at the given position and then shifting the elements of the array. The part which was split will be added to the end of the array.
Algorithm
Follow the algorithm to understand the detailed working of the program.
Step 1- Define a function SplitArray() which will split the array and add the first part to the end
Step 2- Run a loop from the starting index to the index where the array has to be split
Step 3- Inside the loop, store the first element of the array in a variable x
Step 4- Run a loop inside the first loop from starting to the ending index and shift the elements to the left side
Step 5- When all the elements are shifted keep the first element at the last index
Step 6- Repeat the process for all elements which are in the first part of the array
Step 7- Define another function to print the array
Step 8- Specify the array and the position from where the array has to split
Step 9- Call the function and pass the array and the position
Step 10- Print the resultant array
Program
Look at the program below for splitting the array, and adding the first part to the end. We have used the concept of loops in Python in our program. To calculate the length of the array, we have used len() function which is predefined in the Python library.
def SplitArray(arr, n, k):
for i in range(0, k):
x = arr[0]
for j in range(0, n-1):
arr[j] = arr[j + 1]
arr[n-1] = x
arr = [15, 40, 15, 16, 50, 36]
n = len(arr)
position = 2
SplitArray(arr, n, position)
for i in range(0, n):
print(arr[i], end = ' ')
15 16 50 36 15 40
Conclusion
In this tutorial, we have learned how to split an array and then add the first part of the array to the end of the array. The position where the array had to be split is given by the user. The program then displays the result accordingly.