简单排序--冒泡排序

排序原理:
1. 比较相邻的元素。如果前一个元素比后一个元素大,就交换这两个元素的位置。
2. 对每一对相邻元素做同样的工作,从开始第一对元素到结尾的最后一对元素。最终最后位置的元素就是最大值。
排序过程:
例:{4,5,6,3,2,1}

package com.sort;
/*--------------
 *  Author:Real_Q
 *  Date:2021-01-06
 *  Time:10:01
 *  Description:冒泡排序
 * {4,5,6,3,2,1};
---------------*/
public class BubbleSort {
    //排序
    public static void bubbleSort(Comparable[] comparables) {
        //冒泡排序 小------>大

        //排序次数 i
        for (int i = comparables.length - 1; i > 0; i--) {
            //比较大小次数及交换次数 i
            for (int j = 0; j < i; j++) {
                if (Comparable(comparables[j], comparables[j + 1])) {
                    exchange(comparables, j, j +1);
                }
            }
        }
    }
    //比较大小
    public static boolean Comparable(Comparable comparable1, Comparable comparable2) {
        return comparable1.compareTo(comparable2) > 0;
    }
    //交换元素
    public static void exchange(Comparable[] comparable, int leftIndex, int rightIndex) {
        Comparable temp;
        temp = comparable[leftIndex];
        comparable[leftIndex] = comparable[rightIndex];
        comparable[rightIndex] = temp;
    }
}
测试类:
import java.util.Arrays;
import static com.sort.BubbleSort.bubbleSort;

public class TestBubble {
    public static void main(String[] args) {
        Integer[] integers = {4,6,8,7,9,2,10,1};
        bubbleSort(integers);
        System.out.println(Arrays.toString(integers));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值