
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
Shift Array Elements to the Left in Java
Shifting elements in an array is a common problem in programming, often used in tasks like data processing, cyclic rotations, or simulations. In this article, we'll learn how to shift elements of an array to the left in Java,we will be using the Array class of java.util package.
What Is Left Shifting in an Array?
Left shifting means moving all elements of an array to the left by a specified number of positions. For instance:
- Original Array: {1, 2, 3, 4, 5}
- After 1 Left Shift: {2, 3, 4, 5, 1}
- After 2 Left Shifts: {3, 4, 5, 1, 2}
Java program to shift array elements to the left
Storing the first shiftCount elements in temp
System.arraycopy(array, 0, temp, 0, shiftCount);
Shift the remaining elements using arraycopy method
System.arraycopy(array, shiftCount, array, 0, n - shiftCount);
Temporary array to hold shifted elements
int[] temp = new int[shiftCount];
Place the shifted elements from temp at the end
System.arraycopy(temp, 0, array, n - shiftCount, shiftCount);
Example
Below is the code implementation to shift array elements to the left ?
import java.util.Arrays; public class ShiftArrayLeft { public static void main(String[] args) { // Example array int[] array = {1, 2, 3, 4, 5}; // Number of positions to shift int shiftCount = 1; System.out.println("Original Array: " + Arrays.toString(array)); // Perform left shift leftShift(array, shiftCount); System.out.println("Array after left shift: " + Arrays.toString(array)); } // Method to shift array elements to the left public static void leftShift(int[] array, int shiftCount) { int n = array.length; // Reduce shift count if it's larger than array size shiftCount %= n; // Temporary array to hold shifted elements int[] temp = new int[shiftCount]; // Store the first 'shiftCount' elements in temp System.arraycopy(array, 0, temp, 0, shiftCount); // Shift the remaining elements System.arraycopy(array, shiftCount, array, 0, n - shiftCount); // Place the shifted elements from temp at the end System.arraycopy(temp, 0, array, n - shiftCount, shiftCount); } }
Output
Original Array: [1, 2, 3, 4, 5]
Array after left shift: [2, 3, 4, 5, 1]
Conclusion
Shifting array elements to the left in Java is an essential operation, often required in algorithms and data manipulation tasks. The method shown above is efficient, leveraging Java's System.arraycopy() for faster copying of elements. By following the reusable approach, you can handle various scenarios of array shifting with ease.