优化排序

博客提出一个排序需求,数组元素为9,1,2,3,4,5,6,7,8,除首个元素9外其他元素有序,要求数组只排一次后不再继续排序,并给出冒泡和选择两种实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:数组元素为 9,1,2,3,4,5,6,7,8;如何让这列数组只排一次之后不再继续排序,因为除了第一个元素9之外,其他的都是有序的
2种实现方式,冒泡、选择

public class Sort {
public static void main(String[] args) {
//		int[] array = new int[]{3, 2, 5, 8, 1, 9, 4, 6, 7};
        int[] array = new int[]{9, 1, 2, 3, 4, 5, 6, 7, 8};

    for (int i : array) {
        System.out.print(i+" ");
    }
    System.out.println();
    bubbleSort(array);
    for (int i : array) {
        System.out.print(i+" ");
    }
}

/**
 * 冒泡排序
 *
 * @param array
 */
public static void bubbleSort(int[] array) {
    int count=0;  //统计次数
    for(int i=array.length-1;i>0;i--) {
        boolean flag=true; //优化的标识; 如果没有变化,跳出循环
        for (int j = 0; j < i; j++) {
            if (array[j] > array[j + 1]) {
                int temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;//交换
                flag=false;
            }
        }
        if(flag){
            break;
        }

        ++count;
    }
    System.out.println("排序次数:"+count);
}




//选择排序
//3, 1, 5, 8, 2, 9, 4, 6, 7
//9, 1, 2, 3, 4, 5, 6, 7, 8
public static void selectSort(int[] array){
    //将index作为最小值,找到最小值赋值给index
    for(int i=0;i<array.length-1;i++) {
        int index = i;
        for (int j = i+1; j < array.length; j++) {
            if (array[j] < array[index]) {
                index = j;
            }
        }
        /**
         * 如果index==i,证明i就是最小值,那么不用替换数据
         * 如果i不是最小值,就将i下标的元素与最小值index下标的元素替换   
         */
        
        if(index!=i) {//表示打到过最小值
            int temp = array[i];
            array[i] = array[index];
            array[index] = temp;
        }
    }
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值