冒泡排序

冒泡排序算法:

 

 1 package demo;
 2 
 3 public class Bubblesort {
 4     public static void main(String[] args) {// 冒泡排序
 5         int[] a = { 63, 4, 24, 1, 3, 15, 234, 3, 2, 55, 46, 65 }; // 先定义一个数组
 6         Bubblesort store = new Bubblesort();// 定义一个对象
 7         store.sort(a); // 用刚定义的对象调用sort方法
 8     }
 9 
10     public void sort(int a[]) { // 创建sort类
11         for (int i = 1; i < a.length; i++) { //
12             for (int j = 0; j < a.length - i; j++) {
13                 if (a[j] > a[j + 1]) {
14                     int temp = a[j];// 将相比的数值打的先放在temp中;
15                     a[j] = a[j + 1]; // 将刚才相比较小的数值放于a[j]中;
16                     a[j + 1] = temp; // 将刚才比较的数值大的一方放于a[j+1]中;
17                 }
18             }
19         }
20         showArray(a);
21     }
22 
23     public void showArray(int a[]) {
24         for (int i : a) {
25             System.out.print(">" + i);
26         }
27         System.out.println();
28     }
29 
30 }

 

posted @ 2019-01-26 21:07  Good-baby  阅读(232)  评论(0编辑  收藏  举报