冒泡排序和稀疏数组
1 package com.xing.array;
2
3 public class Demo05 {
4 public static void main(String[] args) {
5 int[] a = {3, 5, 1, 7, 2, 4};
6 bubbleSort(a);
7 for (int i : a) {
8 System.out.print(i + " ");
9 }
10 }
11
12 //冒泡排序 升序
13 public static void bubbleSort(int[] arr) {
14 int temp;
15 //外层循环:判断我们要排序的趟数
16 for (int i = 0; i < arr.length - 1; i++) {
17 boolean flag = false;//标志位
18 //一趟中交换数的位置
19 for (int j = 0; j < arr.length - 1 - i; j++) {
20 if (arr[j + 1] < arr[j]) {//升序 arr[j + 1] > arr[j] 降序
21 temp = arr[j + 1];
22 arr[j + 1] = arr[j];
23 arr[j] = temp;
24 flag = true;//如果发生交换,标志位设为true
25 }
26 }
27 if (flag == false) {//没有发生交换,已经有序
28 //跳出循环
29 break;
30 //return;退出方法,两个都可以
31 }
32 }
33 }
34 }
稀疏数组
1 package com.xing.array;
2
3 public class Demo06 {
4 public static void main(String[] args) {
5 int[][] a = new int[5][5];
6 a[1][2] = 11;
7 a[2][3] = 2;
8 //打印数组
9 for (int[] ints : a) {
10 for (int anInt : ints) {
11 System.out.print(anInt + "\t");
12 }
13 System.out.println();
14 }
15
16 //转化为稀疏数组
17 //获取有效值的个数
18 int sum = 0;
19 for (int i = 0; i < 5; i++) {
20 for (int j = 0; j < 5; j++) {
21 if (a[i][j] != 0) {
22 sum++;
23 }
24 }
25 }
26 System.out.println("有效值个数sum = " + sum);
27
28 //2.创建一个稀疏数组的数组
29 int[][] array = new int[sum + 1][3];
30 array[0][0] = 5;//原数组行数
31 array[0][1] = 5;//原数组列数
32 array[0][2] = sum;//原数组有效值个数
33
34 //遍历二维数组,将非0的值,存放在稀疏数组中
35 int count = 0;//有效数字个数
36 for (int i = 0; i < a.length; i++) {
37 for (int j = 0; j < a[i].length; j++) {
38 if (a[i][j] != 0) {
39 count++;
40 array[count][0] = i;
41 array[count][1] = j;
42 array[count][2] = a[i][j];
43 }
44 }
45 }
46 //输出稀疏数组
47 System.out.println("输出稀疏数组");
48 for (int[] ints : array) {
49 for (int anInt : ints) {
50 System.out.print(anInt + "\t");
51 }
52 System.out.println();
53 }
54
55 System.out.println("还原数组");
56 //1.读取稀疏数组 原数组行数 原数组列数
57 int[][] array1 = new int[array[0][0]][array[0][1]];
58
59 //2.给其中的元素还原值
60 for (int i = 1; i < array.length; i++) {
61 array1[array[i][0]][array[i][1]] = array[i][2];
62 }
63 //3.输出还原的数组
64 System.out.println("输出还原的数组");
65 for (int[] ints : array1) {
66 for (int anInt : ints) {
67 System.out.print(anInt + "\t");
68 }
69 System.out.println();
70 }
71 }
72 }
![]()