冒泡排序和优化

一、冒泡排序

java 复制代码
package com.zhk.code.study;


import java.util.Arrays;

public class Bubble {
        /*
        对数组a中的元素进行排序
        */
        public static void sort(Comparable[] a){
                for(int i=a.length-1;i>0;i--){
                        for (int j = 0; j <i; j++) {
                                if (greater(a[j],a[j+1])){
                                        exch(a,j,j+1);
                                }
                        }
                }
        }
        /*
        比较v元素是否大于w元素
        */
        private static boolean greater(Comparable v,Comparable w){
                return v.compareTo(w)>0;
        }
        /*
        数组元素i和j交换位置
        */
        private static void exch(Comparable[] a,int i,int j){
                Comparable t = a[i];
                a[i]=a[j];
                a[j]=t;
        }
        //测试代码
        public static void main(String[] args) {
                Integer[] a = {4, 5, 6, 3, 2, 1};
                Bubble.sort(a);
                System.out.println(Arrays.toString(a));
        }
}

二、优化

第二层循环完毕如果没有更改位置,那么就证明现在顺序是正确的,就不往下面循环了

java 复制代码
package com.zhk.code.study;


import java.util.Arrays;

public class Bubble {
        /*
        对数组a中的元素进行排序
        */
        public static void sort(Comparable[] a){
                Boolean isSkip = true;
                for(int i=a.length-1;i>0;i--){
                        for (int j = 0; j <i; j++) {
                                if (greater(a[j],a[j+1])){
                                        exch(a,j,j+1);
                                        isSkip = false;
                                }

                        }
                        if (isSkip) {
                                break;
                        }
                }
        }
        /*
        比较v元素是否大于w元素
        */
        private static boolean greater(Comparable v,Comparable w){
                return v.compareTo(w)>0;
        }
        /*
        数组元素i和j交换位置
        */
        private static void exch(Comparable[] a,int i,int j){
                Comparable t = a[i];
                a[i]=a[j];
                a[j]=t;
        }
        //测试代码
        public static void main(String[] args) {
                Integer[] a = {1,2,3};
                Bubble.sort(a);
                System.out.println(Arrays.toString(a));
        }
}
相关推荐
做cv的小昊7 分钟前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
摇滚侠32 分钟前
《On Java 中文版 基础卷》阅读笔记 对象无处不在 03
java·笔记·python
لا معنى له34 分钟前
World-In-World: World Models in a Closed-Loop World
算法
二十雨辰1 小时前
[学成在线]-01项目背景
java
弈栈录2 小时前
Java AI 应用的异步化与高并发设计
java·后端·架构
落魄实习生2 小时前
Agent Scope Java 2.x 系列【2】 ReActAgent
java·开发语言
艸肅2 小时前
Ubuntu 安装 JDK (含手动安装)
java·ubuntu·jdk
m0_734172422 小时前
Python字典计数怎样处理首次出现的键
java
卓怡学长3 小时前
w204基于springbo旅行社签证代理服务系统
java·spring boot·spring·intellij-idea
Discipline10293 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法