排序-冒泡-java

 1 public class Test {
 2     public static void main(String[] args) {
 3         int[] arr = {5, 2, 6, 8, 9, 1};
 4         if (arr == null || arr.length <= 2) {
 5             return;
 6         }
 7         for (int end = arr.length - 1; end > 0; end--) {
 8             for (int i = 0; i < end; i++) {
 9                 //冒泡排序的实质就是数组下标 (0,1) (1,2) (2,3)...这样两两进行判断
10                 if (arr[i] > arr[i + 1]) {
11                     swap(arr, i, i + 1);
12                 }
13             }
14         }
15         for (int i = 0; i < arr.length; i++) {
16             System.out.println(arr[i]);
17         }
18     }
19 
20     private static void swap(int[] arr, int i, int j) {
21         arr[i] = arr[i] ^ arr[j];
22         arr[j] = arr[i] ^ arr[j];
23         arr[i] = arr[i] ^ arr[j];
24     }
25 }

 

posted @ 2019-09-29 19:13  青稞123  阅读(135)  评论(0编辑  收藏  举报