Java排序算法优化--冒泡排序【温故而知新】

对于冒泡排序的改进,感谢MoreWindows(微软最有价值专家),给我提供这么好的思路,我只是写了一个完整的Java版本。

/**
 *
 * @author Fly
 */
public class BubbleSort {

    //不加思考写的交换排序
    //不是冒泡排序,比较的不是相邻的元素
    public int[] bubbleSort(int[] a) {
        int size = a.length;
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                if (a[i] > a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
        return a;
    }

    //冒泡排序
    public int[] bubbleSort1(int[] a) {
        int size = a.length;
        for (int i = 0; i < size - i; i++) {
            for (int j = 0; j < size - i - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        return a;
    }

    //改进的冒泡排序
    //改进点:
    //1)增加标志位,标记最终的交换位置,去掉不必要的交换操作;
    //2)如果当前循环没有交换数据,说明已经完成排序,去掉不必要的比较;
    public int[] bubbleSort2(int[] a) {
        int size = a.length;
        for (int i = 0; i < size - 1; i++) {
            //做一个标志位
            int flag = i;
            for (int j = 0; j < size - i - 1; j++) {
                //如果顺序不对,记录需要交换的标志位,以后一次交换位置
                if (a[j] > a[j + 1]) {
                    flag = j;
                }
            }
            //如果标志位更换说明数据顺序不对
            if (flag > i) {
                //交换数据
                int temp = a[i];
                a[i] = a[flag];
                a[flag] = temp;
                //调整再次循环起始位置,因为标志位以后的元素(假如有的话)肯定是顺序的
                i = flag;
            //如果标志位没有变化,那说明数据全部顺位,直接跳出循环
            } else {
                break;
            }
        }
        return a;
    }

    public void printArray(int[] a) {
        for (int i : a) {
            System.out.print(i + ",");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] a = {2, 3, 1, 5, 7, 8, 9, 0, 11, 10, 12, 13, 14, 4, 6};
        BubbleSort bubblesort = new BubbleSort();
        bubblesort.printArray(a);
        bubblesort.printArray(bubblesort.bubbleSort(a));
        bubblesort.printArray(bubblesort.bubbleSort1(a));
        bubblesort.printArray(bubblesort.bubbleSort2(a));
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值