public class Array06 {
public static void main(String[] args) {
int[][] b = { { 11 }, { 21, 22 }, { 31, 32, 33 } };
int result = method(b);
System.out.println("数组的元素和为:" + result);
}
public static int method(int[][] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
result += arr[i][j];
}
}
return result;
}
}
public class Array07 {
public static void main(String[] args) {
int[] arr = setArray();
sortArr1(arr);
method(arr);
}
public static int[] setArray() {
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 100);
}
return arr;
}
public static int[] sortArr(int[] arr) {
for (int j = 0; j < arr.length - 1; j++) {
for (int i = 0; i < arr.length - 1 - j; i++) {
if (arr[i] > arr[i + 1]) {
int team = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = team;
}
}
}
return arr;
}
public static int[] sortArr1(int[] arr) {
for (int x = 0; x < arr.length - 1; x++) {
for (int i = 1 + x; i < arr.length; i++) {
if (arr[x] > arr[i]) {
int team = arr[x];
arr[x] = arr[i];
arr[i] = team;
}
}
}
return arr;
}
public static void method(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.println(arr[i]);
} else {
System.out.print(arr[i] + ",");
}
}
}
}
public class Array05 {
public static void main(String[] args) {
int[] arr = { 3, 12, 24, 36, 55, 68, 75, 88 };
int result = method(arr, 24);
System.out.println(result);
}
public static int method(int[] arr, int num) {
int front = 0;
int end = arr.length - 1;
int min = (front + end) / 2;
for (int i = 0; i < arr.length; i++) {
if (num == arr[min]) {
return min;
} else if (num > arr[min]) {
front = min + 1;
min = (front + end) / 2;
} else {
end = min - 1;
min = (front + end) / 2;
}
}
return -1;
}
}
下面是用封装好的方法实现的
public class Arrays05 {
public static void main(String[] args) {
int[] arr = {3,12,24,36,55,68,75,88};
method(arr);
int index = Arrays.binarySearch(arr,24);
System.out.println(index);
}
public static void method(int[] arr){
Arrays.sort(arr);
}
}