Common algorithms for arrays are foundational in programming, as they enable quick operations like finding values, reversing elements, or shifting positions.
Here’s a breakdown of a few essential array algorithms, each illustrated with simple implementations in Java.
Finding the maximum or minimum value in an array involves iterating through all elements and updating a variable whenever a new max or min is found.
Example Code:
public class ArrayAlgorithms {
public static int findMax(int[] array) {
int max = array[0];
for (int num : array) {
if (num > max) {
max = num;
}
}
return max;
}
public static int findMin(int[] array) {
int min = array[0];
for (int num : array) {
if (num < min) {
min = num;
}
}
return min;
}
}
Reversing an array means swapping the elements from the two ends toward the center. This can be done efficiently in-place without requiring an additional array.
Example Code:
public class ArrayAlgorithms {
public static void reverseArray(int[] array) {
int start = 0;
int end = array.length - 1;
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
}
Shifting elements involves moving each element in the array to a new position. Shifts can be either to the left or right, and may be circular (wrapping around to the other end).
Left Shift by One Position:
public class ArrayAlgorithms {
public static void leftShift(int[] array) {
int first = array[0];
for (int i = 0; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
array[array.length - 1] = first;
}
}
Right Shift by One Position:
public class ArrayAlgorithms {
public static void rightShift(int[] array) {
int last = array[array.length - 1];
for (int i = array.length - 1; i > 0; i--) {
array[i] = array[i - 1];
}
array[0] = last;
}
}
If you want to shift an array by more than one position, a rotating function is more efficient. Here’s an example of left-rotating by n
positions.
Left Rotate by N Positions:
public class ArrayAlgorithms {
public static void leftRotate(int[] array, int n) {
n = n % array.length; // In case n is greater than the array length
reverse(array, 0, n - 1);
reverse(array, n, array.length - 1);
reverse(array, 0, array.length - 1);
}
private static void reverse(int[] array, int start, int end) {
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
}