Split Array and Add First Part to the End in Java



In this article, we will learn how to split an array at a specified position and move the first part of the array to the end in Java. Specifically, the program will allow you to choose a position in the array, shift all elements before that position to the end, and adjust the array accordingly. This is a common way to rotate or rearrange elements in an array. Let's go over the problem and steps to achieve this.

Steps to split the array and add the first part to the end

Following are the steps to split the array and add the first part to the end ?

  • Import all the classes from java.lang and java.util package.
  • Define the split_array method to take the array, its length, and the split position as parameters.
  • We will use a for loop to rotate elements in the array based on the split position.
  • In the main method, initialize the array and set the split position.
  • Call the split_array method with the array, its length, and split position.
  • Print the modified array to display the final arrangement.

Java program to split the array

Following is the Java program to split the array and add the first part to the end ?

import java.util.*;
import java.lang.*;
public class Demo {
   public static void split_array(int my_arr[], int arr_len, int k) {
      for (int i = 0; i < k; i++) {
         int x = my_arr[0];
         for (int j = 0; j < arr_len - 1; ++j)
         my_arr[j] = my_arr[j + 1];
         my_arr[arr_len - 1] = x;
      }
   }
   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, 4, position);
      System.out.println("The array after splitting and rotating is : ");
      for (int i = 0; i < arr_len; ++i)
      System.out.print(my_arr[i] + " ");
   }
}

Output

The array after splitting and rotating is :
78 90 67 45 12 102 34

Code Explanation

A class named Demo contains a function named ?split_array' that takes the array, the length of the array, and a position as its parameters. It iterates through the array up to the position of the array, and the first element in the array is assigned to a variable. Another loop iterates through the length of the array and assigns the second element to the first element. The first element of the array is then assigned to the last position.

In the main function, the array is declared, and the length of the array is stored in a variable. The function ?split_array' is called by passing the array, length, and position where the array needs to be split. The resultant output is displayed by iterating over the array.

Updated on: 2024-11-13T12:19:50+05:30

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements