java中常见排序算法

一、冒泡排序

/**
 * @author liyong
 * @date 2021年12月02日 23:33
 */

public class BubbleSort {
    public static void main(String[] args) {
        int a[] = {6, 3, 8, 2, 9, 1};
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        //排序后的数组顺序为
        for (int res : a) {
            System.out.print(" " + res);
        }
    }
}

二、选择排序

/**
 * @author liyong
 * @date 2021年12月02日 23:39
 */

public class SelectSort {
    public static void main(String[] args) {
        int a[] = {6, 3, 8, 2, 9, 1};
        //外层控制总共要进行排序的趟数
        for (int x = 0; x < a.length - 1; x++) {
            //内层表示要和下标为X的数据比较数组值
            for (int y = x + 1; y < a.length; y++) {
                if (a[x] > a[y]) {
                    int temp = a[y];
                    a[y] = a[x];
                    a[x] = temp;
                }
            }
        }
        //排序后的数组顺序为
        for (int res : a) {
            System.out.print(" " + res);
        }
    }
}

三、插入排序

/**
 * @author liyong
 * @date 2021年12月02日 23:42
 */

public class InsertionSort {
    public static void main(String[] args) {
        int a[] = {6, 8, 2, 4, 1, 6, 3};
        //N个数,则需要进行n-1次排序
        //从第一个元素开始,该元素可以认为已经被排序
        for (int i = 0; i < a.length - 1; i++) {
            //取出下一个元素,在已经排序的元素序列中从后向前扫描
            for (int j = i + 1; j > 0; j--) {
                //如果该元素(已排序)大于新元素,将该元素移到下一位置
                if (a[j] < a[j - 1]) {
                    int temp = a[j];
                    a[j] = a[j - 1];
                    a[j - 1] = temp;
                }
            }
        }
        //重新输出
        for (int res : a
        ) {
            System.out.print(" " + res);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值