码迷,mamicode.com
首页 > 编程语言 > 详细

冒泡排序(java版)

时间:2015-03-19 14:31:45      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

 1 public class BubbleSortTest {
 2     //冒泡排序
 3     public static void bubbleSort(int[] source) {
 4         //外层循环控制控制遍历次数,n个数排序,遍历n - 1次
 5         for (int i = source.length - 1; i > 0; i--) {
 6             //每完成一趟遍历,下标为i的位置的元素被确定,下一遍历不再参与比较
 7             for (int j = 0; j < i; j++) {
 8                 if (source[j] > source[j + 1]) {
 9                     swap(source, j, j + 1);
10                 }
11             }
12         }
13     }
14     //private 完成交换功能的子函数
15     private static  void swap(int[] source, int x, int y) {
16         int temp = source[x];
17         source[x] = source[y];
18         source[y] = temp;
19     }
20     //在main中测试
21     public static void main(String[] args) {
22         int[] a = {4, 2, 1, 6, 3, 6, 0, -5, 1, 1};
23         
24         bubbleSort(a);
25         //局部变量要初始化
26         for (int i = 0; i < a.length; i++) {
27             //利用printf进行格式化输出
28             System.out.printf("%d ",a[i]);
29         }
30     }
31 }

 

冒泡排序(java版)

标签:

原文地址:http://www.cnblogs.com/happyhacking/p/4350243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!