冒泡排序-java实现

  1. /**
  2. * 冒泡排序:相邻元素两两比较,每趟都将最大元素调整到最后面
  3. * 稳定的排序算法
  4. */
  5. public class BubbleSort {
  6. public void bubbleSort(int[] a) {
  7. for (int i = a.length-1; i > 0; i--) {
  8. for (int j = 0; j < i; j++) {
  9. if (a[j] > a[j + 1]) {// 每一趟比较都找到最大的数
  10. int temp = a[j];
  11. a[j] = a[j + 1];
  12. a[j + 1] = temp;
  13. }
  14. }
  15. }
  16. }
  17. public static void main(String[] args) {
  18. PrintUtil.print("冒泡排序");
  19. int[] a = { 10, 8, 3, 9, 47, 12, 14, 8, 5, 0, 2 };
  20. BubbleSort sort = new BubbleSort();
  21. sort.bubbleSort(a);
  22. PrintUtil.printArray(a, PrintUtil.HORIZONTAL);
  23. }
  24. }

  1. public class PrintUtil {
  2. public static final int HORIZONTAL = 0;
  3. public static void print(String str) {
  4. System.out.println(str);
  5. }
  6. public static void printArray(int[] array, int confi) {
  7. if (confi == HORIZONTAL) {
  8. printHorizonal(array);
  9. } else {
  10. printArray(array);
  11. }
  12. }
  13. private static void printHorizonal(int[] array) {
  14. for (int i = 0; i < array.length; i++) {
  15. System.out.print(array[i] + ", ");
  16. }
  17. System.out.println("");
  18. }
  19. public static void printArray(int[] a) {
  20. for (int i = 0; i < a.length; i++) {
  21. print("元素" + (i + 1) + ":" + a[i]);
  22. }
  23. }
  24. public static void printArray(String[] str) {
  25. for (int i = 0; i < str.length; i++) {
  26. System.out.print(str[i] + ", ");
  27. }
  28. System.out.println("");
  29. }
  30. }

结果打印:

冒泡排序

0, 2, 3, 5, 8, 8, 9, 10, 12, 14, 47, 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值