一、冒泡排序算法
public class BubbleSort {
public static void main(String[] args) {
int[] array = { 8, 5, 6, 7, 2, 1, 9, 4, 3 };
System.out.println("冒泡排序前:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
System.out.print("第" + (i + 1) + "排序:");
for (int k = 0; k < array.length; k++) {
System.out.print(array[k] + " ");
}
System.out.println();
}
System.out.println("冒泡排序后:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
冒泡排序的具体执行过程图:
交换步骤:
二、当二维数组里面里面的数组中每个元素的长度不确定时,可以用一下的以下方式:
int[][] arr = new int[3][];
比如以下例子:
public class Exercise01 {
public static void main(String[] args) {
int[][] arr = new int[3][];
arr[0] = new int[] { 20, 30, 65 };
arr[1] = new int[] { 20, 16, 80, 40, };
arr[2] = new int[] { 20, 18, 50, 32, 60 };
int sum = 0;
for (int i = 0; i < arr.length; i++) {
System.out.println("第" + (i + 1) + "组销售额:");
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
// 求每组销售的总业绩
for (int i = 0; i < arr.length; i++) {
int groupSum = 0;
for (int j = 0; j < arr[i].length; j++) {
groupSum += arr[i][j];
}
sum += groupSum;
System.out.println("第" + (i + 1) + "组总的销售额:" + groupSum + "万元");
}
System.out.println("这个月总的销售额:" + sum + "万元");
}
}
二、当二维数组里面里面的数组中每个元素的长度不确定时,可以用一下的以下方式:
int[][] arr = new int[3][];
比如以下例子:
public class Exercise01 {
public static void main(String[] args) {
int[][] arr = new int[3][];
arr[0] = new int[] { 20, 30, 65 };
arr[1] = new int[] { 20, 16, 80, 40, };
arr[2] = new int[] { 20, 18, 50, 32, 60 };
int sum = 0;
for (int i = 0; i < arr.length; i++) {
System.out.println("第" + (i + 1) + "组销售额:");
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
// 求每组销售的总业绩
for (int i = 0; i < arr.length; i++) {
int groupSum = 0;
for (int j = 0; j < arr[i].length; j++) {
groupSum += arr[i][j];
}
sum += groupSum;
System.out.println("第" + (i + 1) + "组总的销售额:" + groupSum + "万元");
}
System.out.println("这个月总的销售额:" + sum + "万元");
}
}