冒泡排序(java版)

java

 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版) 的全部内容, 来源链接: utcz.com/z/389735.html

回到顶部