冒泡排序

 1 import java.util.Arrays;
 2 
 3 public class test7 {
 4     /**
 5      * 
 6      * @param arr
 7      */
 8     public static void bubbleSort(int[] arr) {
 9         for (int i = 0; i < arr.length-1; i++) {
10             //length-1表示下标在0--length-1
11             for (int j = 0; j < arr.length-1-i; j++) {
12                 //下标j<length-i表示有i个数已经沉入底部,不用在做比较
13                 if(arr[j] > arr[j+1]) {
14                     int tmp = arr[j];
15                     arr[j] = arr[j+1];
16                     arr[j+1] = tmp;
17                 }
18             }
19         }
20     }
21     public static void main(String[] args) {
22         int[] array = {1,22,4,14,2};
23         bubbleSort(array);
24         System.out.println(Arrays.toString(array));
25     }
26 }

 

posted @ 2020-05-04 16:56  听说在北郭  阅读(88)  评论(0)    收藏  举报