数组应用
1.应用
package com.array.Array;
import java.util.Arrays;
//Array类的应用
public class ArrayDemo07 {
public static void main(String[] args) {
int[] a = {123,44,5588,999,44,71,62,2,7,8883};
System.out.println(a);//仅仅是一个内存地址
//打印数组元素
//System.out.println(Arrays.toString(a));//完整数组内容
printArray(a);
System.out.println();
Arrays.sort(a);//排序
System.out.println(Arrays.toString(a));
Arrays.fill(a,0);//全部填充
System.out.println(Arrays.toString(a));
Arrays.fill(a,2,4,0);//第二个到第四个数之间
System.out.println(Arrays.toString(a));
}
public static void printArray(int[] a){
for (int i = 0; i < a.length; i++) {
if (i==0){
System.out.print("[");
}
if (i==a.length-1){
System.out.print(a[i]+"]");
}else {
System.out.print(a[i]+",");
}
}
}
}
2.冒泡排序
package com.array.Array;
import java.util.Arrays;
//冒泡排序,一共有八大排序方法
public class ArrayDemo08 {
public static void main(String[] args) {
//冒泡排序
//1.比较数组中,两个相邻的元素,如果第一个数比第二个数大,就交换他们的位置
//2.每一次比较,都会产生一个最大或最小的数字
//3.下一轮则可以少一次排序
//4.依次循环,直至结束
int[] a = {123,44,5588,999,44,71,62,2,7,555,8883};
int[] sort = sort(a);
System.out.println(Arrays.toString(sort));
}
public static int[] sort(int[] array){
//临时变量
int temp = 0;
//外层循环,判断一共要走多少次程序;
for (int i = 0; i < array.length; i++) {
boolean flag = false;//通过flag标志位减少没有意义的比较
//内层循环,比较两个数,然后交换值
for (int j = 0; j < array.length-1-i; j++) {
if (array[j+1]<array[j]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
flag = true;
}
}
if (flag==false){
break;
}
}
return array;
}
}
3.稀疏数组
package com.array.Array;
import java.util.Arrays;
//稀疏数组
public class ArrayDemo09 {
public static void main(String[] args) {
//1.创建一个二维数组11*11, 0:没有棋子, 1:黑棋 2:白棋
int[][] array1 = new int[11][11];
array1[1][2] = 1;
array1[2][3] = 2;
//输出原始数组
System.out.println("输出原始数组:");
for (int[] ints : array1) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
System.out.println("=========================");
//转换为稀疏数组
//获取有效值的个数
int sum = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1.length; j++) {
if (array1[i][j]!=0){
sum++;
}
}
}
System.out.println("有效值的个数为:"+sum);
//2.创建一个稀疏数组
int[][] array2 = new int[sum+1][3];
array2[0][0] = 11;
array2[0][1] = 11;
array2[0][2] = sum;
//遍历原来的二维数组,将非零的值存放到稀疏数组
int count = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i][j]!=0){
count++;
array2[count][0] = i;
array2[count][1] = j;
array2[count][2] = array1[i][j];
}
}
}
//输出稀疏数组
System.out.println("输出稀疏数组:");
for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i][0]+"\t"
+array2[i][1]+"\t"
+array2[i][2]+"\t");
}
System.out.println("==================");
//将稀疏数组还原
//1.读取稀疏数组
int[][] array3 = new int [array2[0][0]][array2[0][1]];
//2.给其中的元素还原值
for (int i = 1; i < array2.length; i++) {
array3[array2[i][0]][array2[i][1]] = array2[i][2];
}
//输出还原始数组
System.out.println("输出原始数组:");
for (int[] ints : array3) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
}
}