java - 基础 - 排序

冒泡排序

    //冒泡排序, type = 0 则从小到大, type = 1则从大到小
    //遍历一遍如果后面的比前面的小(大),则两者交换,遍历length-1遍
    public void bubbleSort(int a[], int type){
        for(int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1; j++) {
                if ( (a[j] > a[j + 1] && type==0) || (a[j] < a[j + 1] && type == 1) ){
                    int n = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = n;
                }
                //showArray(a);
            }
        }
    }

 

 

 

 选择排序

    //选择排序, type = 0 则从小到大, type = 1则从大到小
    //遍历一遍选出前i个中最小(大)的和a[i-1]交换。i从length到1;
    public void selectionSort(int a[], int type){
        for(int i = a.length-1; i >= 0; i--) {
            int flag = 0;
            for (int j = 0; j <= i; j++) {
                if ( (a[flag] > a[j] && type==0) || (a[flag] < a[j] && type == 1) ){
                    flag = j;
                }
                //showArray(a);
            }
            int n = a[i];
            a[i] = a[flag];
            a[flag] = n;
        }
    }

 

插入排序

    //插入排序, type = 0 则从小到大, type = 1则从大到小
    //从第i个数字开始(i之前的数字都已经排序完毕),如果第i个数字比它前面的大(小),则说明前i个数字没有排好顺序(第i个数字的位置不对),则把第i个数字记录下来,往前遍历,找到合适的位置插入,依次从第2个数字检查到第length个数字。
    public void insertionSort(int a[], int type){
        for(int i = 1; i < a.length; i++){
            int current = a[i];
            int j = i;
            while( (j>0 && current < a[j-1] && type == 0) || (j>0 && current > a[j-1] && type == 1) ) {//当current比a[j-1]数字小(大)时,说明current应该在这个数字之前,则把这个数字往后挪一格。
                a[j] = a[j-1];
                j--;
            }
            a[j] = current; //当循环结束时,说明目前a[j]之前的数字比current小(大),所以current存在a[j]。
        }
    }

 

转载于:https://www.cnblogs.com/clamp7724/p/11590218.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值