话说上一节提到可以用static来定义一些工具类,啥也不多说,直接撸上吧!
/*
定义数组工具类
1:定义一个遍历数组的函数
2:定义一个求数组和的功能函数 1) 遍历 2) 两两相加
3:定义一个获取数组最大值的功能函数
4:定义一个获取数组最大值角标的功能函数
5:定义一个返回指定数在指定数组中包含的角标的功能函数
6:定义一个可以用于排序int数组的函数
1)冒泡排序
2)选择排序
*/
class Arrays {
private Arrays() {
}
// 1:定义一个遍历数组的函数
public static void print(int[] arr) {
for (int x = 0; x < arr.length; x++) {
if (x != (arr.length - 1)) {
System.out.print(arr[x] + ",");
} else {
System.out.print(arr[x]);
}
}
}
// 2:定义一个求数组和的功能函数
public static int getSum(int[] arr) {
int sum = 0;
for (int x = 0; x < arr.length; x++) {
sum += arr[x];
}
return sum;
}
// 3:定义一个获取数组最大值的功能函数
public static int getMax(int[] arr) {
int max = 0;
for (int x = 0; x < arr.length; x++) {
if (arr[max] < arr[x]) {
max = x;
}
}
return arr[max];
}
// 4:定义一个获取数组最大值角标的功能函数
public static int getIndexMax(int[] arr) {
int max = 0;
for (int x = 0; x < arr.length; x++) {
if (arr[max] < arr[x]) {
max = x;
}
}
return max;
}
// 5:定义一个返回 指定数在指定数组中包含的角标的功能函数
public static int getIndex(int[] arr, int src) {
int index = -1;
for (int x = 0; x < arr.length; x++) {
if (arr[x] == src) {
index = x;
}
}
return index;
}
// 冒泡
public static void test(int[] arr) {
for (int x = 0; x < arr.length - 1; x++) {
if (arr[x] > arr[x + 1]) {
int temp = arr[x + 1];
arr[x + 1] = arr[x];
arr[x] = temp;
}
}
}
// 选择排序
public static void selectSort(int[] arr) {
for (int x = 0; x < arr.length - 1; x++) {
for (int y = 1 + x; y < arr.length; y++) {
if (arr[x] > arr[y]) {
int temp = arr[y];
arr[y] = arr[x];
arr[x] = temp;
}
}
}
}
// 7:定义一个可以将整数数组进行反序的功能函数。
public static void reverseSort(int[] arr) {
int start = 0;
int end = arr.length - 1;
for (int x = 0; x < arr.length; x++) {
if (start < end) {
int tem = arr[start];
arr[start] = arr[end];
arr[end] = tem;
}
start++;
end--;
}
}
// 折半查找(二分法)
public static int halfSearch(int key, int[] arr) {
int min = 0;
int max = arr.length - 1;
int mid = 0;
while (min < max) {
mid = (min + max) / 2;
if (key > arr[mid]) {
min = mid + 1;
} else if (key < arr[mid]) {
max = mid - 1;
} else {
return mid;
}
}
return -1;
}
}
class MyClass {
//主函数
public static void main(String[] args) {
int[] arr = { 1, 3, 5, 2, 1, 7, 3};//声明一个数组
Arrays.print(arr);
System.out.println();
Arrays.selectSort(arr);
Arrays.print(arr);
}
}