冒泡排序

来源:互联网 发布:淘宝卖家视频怎么上传 编辑:程序博客网 时间:2024/05/23 18:28

           昨天有人问冒泡是怎么用java实现的,所以今天就和大家分享一下我的想法。实现代码如下:

         

           public class MaoPao {

                     public static void main(String[] args) {

                               int a[] = { 12, 23, 435, 6, 2, 4, 543, 226, 595 };

                               int i, j, n, temp;

                               // 数组的长度

                               n = a.length;

                                for (j = 0; j < n; j++) {

                                       for (i = 0; i < n - j; i++) {

                                                 try {

                                                                 // 把最大的交换到最后面去

                                                                if (a[i] > a[i + 1]) {

                                                                            temp = a[i];

                                                                            a[i] = a[i + 1];

                                                                            a[i + 1] = temp;

                                                                   }

                                                  } catch (Exception e) {

                                                // TODO: handle exception

                                                 }

                                  }

                   }

                   for (i = 0; i < n; i++) {

                            System.out.print(a[i] + " ");

                   }

           }

     }

2 0
原创粉丝点击