The following method demonstrates how to reverse the elements of one array into another:
public static void reverseArray(int[] source, int[] destination) {
for (int i = source.length - 1, j = 0; i >= 0; i--, j++) {
destination[j] = source[i];
}
}
This approach uses two pointers: one starting at the end of the source array and the other at the beginning of the destination array, effectively copying elements in reverse order.
Working with Two-Dimensional Arrays
Below is an example showing how to declare and iterate through a 2D array:
int[][] matrix = {{1, 2}, {2, 3}, {3, 4}, {4, 5}};
System.out.println(matrix.length); // Outputs: 4
System.out.println(matrix[0].length); // Outputs: 2
System.out.println("==================");
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
/*
Output:
1 2
2 3
3 4
4 5
*/
Utilizing the Arrays Class
The Arrays class provides useful utility methods for handling arrays:
int[] numbers = {1, 2, 343, 65645, 77777, 12};
System.out.println(numbers); // Prints hash code representation
System.out.println(Arrays.toString(numbers));
// Output: [1, 2, 343, 65645, 77777, 12]
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
// Output: [1, 2, 12, 343, 65645, 77777]
toString()converts an array into a reaadble string format.sort()arranges the elements in ascending order.fill()assigns a specified value to a range within the array (left inclusive, right exclusive).
int[] data = {2, 4, 1, 6, 3, 5};
Arrays.fill(data, 2, 4, 0);
System.out.println(Arrays.toString(data));
// Output: [2, 4, 0, 0, 3, 5]
Arrays.fill(data, 0);
System.out.println(Arrays.toString(data));
// Output: [0, 0, 0, 0, 0, 0]
Bubble Sort Implementation and Optimization
Here's a standard implementation of the bubble sort algorithm along with an optimized version:
public static void bubbleSort(int[] arr) {
for (int round = 0; round < arr.length - 1; round++) {
for (int index = 0; index < arr.length - 1 - round; index++) {
if (arr[index] > arr[index + 1]) {
int temp = arr[index];
arr[index] = arr[index + 1];
arr[index + 1] = temp;
}
}
}
}
public static void bubbleSortOptimized(int[] arr) {
boolean swapped = false;
int temp = 0;
for (int round = 0; round < arr.length - 1; round++) {
swapped = false;
for (int index = 0; index < arr.length - 1 - round; index++) {
if (arr[index] > arr[index + 1]) {
temp = arr[index];
arr[index] = arr[index + 1];
arr[index + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
}