冒泡排序
- 冒泡排序无疑是最为出名的排序算法之一,总共有八大排序!
- 冒泡的代码还是相当简单的,两层循环,外层冒泡轮数,里层依次比较。
- 看到嵌套循环,应该立马就可以得出这个算法的时间复杂度为O(n2)。
public class ArrayDem09 {
public static void main(String[] args) {
int[] a = {23, 43, 13, 56, 45, 32, 64};
int[] sort = sort(a);
System.out.println(Arrays.toString(sort));
}
public static int[] sort(int[] array) {
int x = 0;
for (int i = 0; i < array.length; i++) {
boolean flag = false;
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
x = array[j];
array[j] = array[j + 1];
array[j + 1] = x;
flag=true;
}
}
if (flag==false);
break;
}
return array;
}
}
输出结果:
[23, 13, 43, 45, 32, 56, 64]
稀疏数组
- 当一个数组中大部分元素为0,或者为同一值的数组时,可以使用稀疏数组来保存该数组。
- 稀疏数组的处理方试:
- 记录稀疏数组一共有几行几列,有多少不同的值
- 把具有不同值元素和行列及值记录在一个小规模的数组中,从而缩小程序的规模
- 左边是原始数据,右边是稀疏数组
public class ArrayDem10 {
public static void main(String[] args) {
int[][]array1 = new int[11][11];
array1 [1][2]=1;
array1 [2][3]=2;
System.out.println("输出原始数组:");
for (int[] x :array1) {
for (int i : x) {
System.out.print(i+"\t");
}
System.out.println( );
}
int sum= 0;
for (int i = 0; i <11 ; i++) {
for (int j = 0; j <11 ; j++) {
if (array1[i][j]!=0){
sum++;
}
}
}
System.out.println("获取有效值的个数:"+sum);
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 < array1[i].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]);
}
int[][]array3=new int[array2[0][0]][array2[0][1]];
for (int i = 1; i < array2.length; i++) {
array3[array2[i][0]][array2[i][1]] = array2[i][2];
}
System.out.println("输出还原的数组:");
for (int[] x :array1) {
for (int i : x) {
System.out.print(i+"\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 1
2 3 2
输出还原的数组:
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