Attays类
package Array;
import java.util.Arrays;
public class attay5 {
public static void main(String[] args) {
int[] a={2,4,5,7,6,1};
//System.out.println(a);
//打印数组元素 toString
//odd(a);
//排序数组 sort()
// Arrays.sort(a);
//System.out.println(Arrays.toString(a));
//数组填充
//Arrays.fill(a,0);
Arrays.fill(a,2,4,0);
System.out.println(Arrays.toString(a));
}
//自己写打印数组元素
/*
publi static void odd(int[] a)
for(i=0;i<a.length;i++)
if(i==0)
sout("[")
if(i==a.length-1)
sout(a[i]+"]")
else
sout(a[i]+" ")
*/
//排序
}
[2, 4, 0, 0, 6, 1]
冒泡排序
package Array;
import java.util.Arrays;
public class maopao {
public static void main(String[] args) {
int[] a = {2, 7, 4, 9, 6, 5};
int[] add = add(a);
System.out.println(Arrays.toString(a));
}
/*
冒泡排序
1,比较相邻的两个数,如果第一个比第二个大或小,就交换位置
2,每一次比较,都会产生一个最大或最小的
3,下一轮可以减少一次排序
4,依次循环,直到结束
*/
public static int[] add(int[] a) {
boolean flag =false;//通过flag标识位减少没有比较的比较——优化(加不加都可以)
int b = 0;
//外层循环,判断段我们走多少次
for (int i = 0; i < a.length; i++) {
//比较,阿。length-1-i,四个数只需比三次
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j + 1] < a[j]) {
b = a[j];
a[j] = a[j + 1];
a[j + 1] = b;
//flag=true——优化
}
}
//if(flag==false){——优化
//break;——优化
//}——优化
}
return a;
}
}
[2, 4, 5, 6, 7, 9]
稀疏数组
package Array;
public class xishu {
public static void main(String[] args) {
int[][] a = new int[11][11];
a[1][2] = 1;
a[2][3] = 2;
System.out.println("输出原始的数值");
for (int[] ints : a) {
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
//转换稀疏数组保存
//获取有效值的个数
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (a[i][j] != 0) {
sum++;
}
}
}
System.out.println("有效值个数" + sum);
//创建一个稀疏数组的数组
int[][] b = new int[sum + 1][3];
b[0][0] = 11;
b[0][1] = 11;
b[0][2] = sum;
//遍历二维数组,将非零值,存放稀疏数组中
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {//第一行有几个长度
if (a[i][j] != 0) {
count++;
b[count][0] = i;
b[count][1] = j;
b[count][0] = a[i][j];
}
}
}
//输出稀疏数组
System.out.println("稀疏数组");
for (int i = 0; i < b.length; i++) {
System.out.println(b[i][0] + "\t" + b[i][1] + "\t" + b[i][2] + "\t");
}
System.out.println("还原");
//先读取稀疏数组
int[][] c = new int[b[0][0]][b[0][1]];
//给其中的元素还原它的值
for (int i = 1; i < b.length; i++) {
c[b[i][0]][b[i][1]] = b[i][2];
}
//打印
System.out.println("输出还原的数值");
for (int[] ints : c) {
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
}
}
输出原始的数值
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
有效值个数2
稀疏数组
11 11 2
1 2 0
2 3 0
还原
输出还原的数值
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
study 6:30h