Day05_java数组
冒泡排序
package com.shan.array;
public class Demo01 {
public static void main(String[] args) {
int[] a = {123,4,5,6655,7567,8,4,2,57,2};
int[] sorted= sortMaopao(a);
for (int i = 0; i < sorted.length; i++) {
System.out.println(sorted[i]);
}
for (int k = 0; k < sorted.length; k++) {
System.out.println(a[k]);
}
}
public static int[] sortMaopao(int[] a) {
int tmp = 0;
int[] result=a;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length-i-1; j++) {
if (result[j] > result[j + 1]) {
tmp = result[j];
result[j]=result[j + 1];
result[j + 1]=tmp;
}
}
}
return result;
}
}
输出结果:
2 2 4 4 5 8 57 123 6655 7567
2 2 4 4 5 8 57 123 6655 7567
此时数组a的顺序也变了,目前的知识还无法解答,留到以后解答吧!
稀疏数组
package com.shan.array;
public class Demo02 {
public static void main(String[] args) {
int[][] a = new int[11][11];
a[3][5] = 5;
a[7][9] = 10;
for (int i = 0; i < a[0].length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < a[0].length; i++) {
for (int j = 0; j < a[0].length; j++) {
if (a[i][j] != 0) {
sum++;
}
}
}
//稀疏数组
int[][] compress = new int[sum + 1][3];
compress[0][0] = a[0].length;
compress[0][1] = a[0].length;
compress[0][2] = sum;
int count = 0;
for (int m = 0; m < a[0].length; m++) {
for (int n = 0; n < a[0].length; n++) {
if (a[m][n] != 0) {
count++;
compress[count][0] = m;
compress[count][1] = n;
compress[count][2] = a[m][n];
}
}
}
for (int m = 0; m < compress[0].length; m++) {
for (int n = 0; n < 3; n++) {
System.out.print(compress[m][n] + " ");
}
System.out.println();
}
}
}
输出结果:
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 5 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 10 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
11 11 2
3 5 5
7 9 10