冒泡排序

选择排序代码体现:

 1 public class ArrayDemo {
 2     public static void main(String[] args) {
 3         // 定义一个数组
 4         int[] arr = { 9, 5, 4, 3, 2, 1, 67, 8 };
 5         printArr(arr);
 6         System.out.println("");
 7         // 排序后的数组
 8         bubbleSort(arr);
 9     }
10     // 定义排序数组的功能
11     public static void bubbleSort(int[] arr) {
12         //外层循环控制内层数据比较的次数,
13         for (int y = 0; y < arr.length - 1; y++) {
14             for (int x = 0; x < arr.length - 1 - y; x++) {
15                 if (arr[x] > arr[x + 1]) {
16                     // 一旦前一个索引处的值比后一个大则交换两处的值
17                     int temp = arr[x];
18                     arr[x] = arr[x + 1];
19                     arr[x + 1] = temp;
20                 }
21             }
22         }
23         //打印数组
24         printArr(arr);
25     }
26     // 遍历数组的功能
27     public static void printArr(int[] arr) {
28         System.out.print("[");
29         for (int x = 0; x < arr.length; x++) {
30             if (x == arr.length - 1) {
31                 System.out.print(arr[x] + "]");
32             } else {
33                 System.out.print(arr[x] + ", ");
34             }
35         }
36     }
37 }

原文地址:https://www.cnblogs.com/fuck1/p/5373574.html