
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to split the array and add the first part to the end
Our task is to write a Java program to split the array and add the first part to the end. Here, the value of k=2, which means we need to keep 2 elements at the end of the array.
Input: 67, 45, 78, 90, 12, 102, 34 Output: 78, 90, 12, 102, 34, 67, 45
Split the Java Array, Add the First Part to the End
The following are the approaches to split the array and add the first part to the end:
By Shifting Elements
In this program, we will shift the elements one by one if we have:
my_arr = {67, 45, 78, 90, 12, 102, 34} k = 2
We reverse only the first k elements: {67, 45} becomes {45, 67}.
{45, 67, 78, 90, 12, 102, 34}
We reverse the remaining elements: {78, 90, 12, 102, 34} becomes {34, 102, 12, 90, 78}.
{45, 67, 34, 102, 12, 90, 78}
Example
The following is the Java program to split the array and add the first part to the end using the shifting elements:
public class Demo { public static void split_array(int my_arr[], int arr_len, int k) { for (int i = 0; i < k; i++) { int first = my_arr[0]; for (int j = 0; j < arr_len - 1; ++j) { my_arr[j] = my_arr[j + 1]; } my_arr[arr_len - 1] = first; } } public static void main(String[] args) { int my_arr[] = { 67, 45, 78, 90, 12, 102, 34 }; int arr_len = my_arr.length; int position = 2; split_array(my_arr, arr_len, position); System.out.println("The array after splitting and rotating is : "); for (int num : my_arr) { System.out.print(num + " "); } } }
Following is the output of the above program:
The array after splitting and rotating is :
78 90 12 102 34 67 45
Using the Reversal Method
We are going to use the reversal method as we can rotate the whole section of the array at once, instead of shifting each element many times, we just swap pairs in-place.
Example
Below is an example to split the array and add the first part to the end using the reversal method:
public class Demo { public static void reverse(int[] arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } public static void split_array(int[] arr, int k) { int n = arr.length; k = k % n; reverse(arr, 0, k - 1); reverse(arr, k, n - 1); reverse(arr, 0, n - 1); } public static void main(String[] args) { int[] my_arr = { 67, 45, 78, 90, 12, 102, 34 }; int position = 2; split_array(my_arr, position); System.out.println("The array after splitting and rotating is : "); for (int num : my_arr) { System.out.print(num + " "); } } }
Following is the output of the above program:
The array after splitting and rotating is : 78 90 12 102 34 67 45