Java编写程序:用泛型写数组元素倒置,数组元素分拆,数组元素合并
时间: 2024-10-08 18:27:13 浏览: 37
Java泛型应用:数组反转技术与代码实现
在Java中,可以利用泛型(Generics)来编写一些通用的函数,例如倒置数组、分拆数组和合并数组。这里简单提供一个示例:
```java
import java.util.Arrays;
public class ArrayUtils<T> {
// 数组元素倒置
public static T[] reverseArray(T[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
T temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
return arr;
}
// 数组元素分拆成两部分
public static T[][] splitArray(T[] arr, int partitionIndex) {
if (partitionIndex > arr.length) {
throw new IllegalArgumentException("Partition index is out of bounds");
}
T[] firstPart = Arrays.copyOfRange(arr, 0, partitionIndex);
T[] secondPart = Arrays.copyOfRange(arr, partitionIndex, arr.length);
return new T[][] {firstPart, secondPart};
}
// 合并两个已排序的数组
public static <T extends Comparable<T>> T[] mergeSortedArrays(T[] array1, T[] array2) {
T[] mergedArray = Arrays.copyOf(array1, array1.length + array2.length);
mergeSort(mergedArray, 0, array1.length - 1);
mergeSort(mergedArray, array1.length, mergedArray.length - 1);
merge(mergedArray, array1.length, array2.length - 1);
return mergedArray;
}
private static void merge(T[] arr, int left, int right) {
int i = left, j = right, k = left;
while (i <= j) {
if (arr[i].compareTo(arr[j]) <= 0) {
arr[k++] = arr[i++];
} else {
arr[k++] = arr[j--];
}
}
}
private static void mergeSort(T[] arr, int low, int high) {
if (low < high) {
int mid = low + (high - low) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);
merge(arr, low, mid, high);
}
}
}
// 使用示例:
Integer[] numbers = {1, 3, 5, 7, 9};
Integer[] reversedNumbers = ArrayUtils.reverseArray(numbers); // [9, 7, 5, 3, 1]
Integer[][] splitNumbers = ArrayUtils.splitArray(numbers, 3); // [[1, 3, 5], [7, 9]]
Integer[] mergedNumbers = ArrayUtils.mergeSortedArrays(numbers, new Integer[]{4, 6, 8}); // [1, 3, 4, 5, 6, 7, 8, 9]
```
阅读全文