思路:
1.二维数组转变为一维数组
1.1 循环遍历,嵌套嵌套嵌套
2.一维数组排序
2.1 一维数组的长度是二维数组的元素的个数
2.2 一维数组的排序方式(算法)
3.一维数组按照二维数组的格式重新赋值
3.1函数重载
package hw;
import java.util.Arrays;
public class lx {
public static void main(String[] args) {
int[][] arr = {{10, 20, 50}, {30, 40, 80, 55}, {15, 100}};
int i2 = CountArr(arr);
System.out.println("二维数组的元素个数:" + i2);
int[] arr2 = new int[CountArr(arr)];
printArr(arr);
arr2 = returnToArr(arr);
System.out.println();
System.out.println("将二维数组转化为一维数组之后");
printArr(arr2);
System.out.println("数组和:" + arrSum(arr2));
int[] sort = sort(arr2);
System.out.println("输出排序后的一维数组");
printArr(sort);
for (int i = 0, x2 = 0; i < arr.length; i++) {
for (int i1 = 0; i1 < arr[i].length; i1++) {
arr[i][i1] = sort[x2++];
}
}
printArr(arr);
}
public static int[] sort(int[] sourceArray) {
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (i != min) {
int tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;
}
}
return arr;
}
public static int arrSum(int[] arr) {
int sum = 0;
for (int value : arr) {
sum += value;
}
return sum;
}
public static void printArr(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void printArr(int[][] arr) {
for (int[] ints : arr) {
for (int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
}
public static int CountArr(int[][] arr) {
int count = 0;
for (int[] ints : arr) {
for (int anInt : ints) {
count++;
}
}
return count;
}
public static int[] returnToArr(int[][] arr) {
int[] arr2 = new int[CountArr(arr)];
for (int i = 0, x = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
arr2[x++] = arr[i][j];
}
}
return arr2;
}
}