冒泡排序和优化

一、冒泡排序

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));
        }
}
相关推荐
骄马之死7 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
Frostnova丶7 小时前
【算法笔记】数学知识
笔记·算法
吴可可1238 小时前
AutoCAD 2016与2014二次开发关键差异
算法
郑洁文8 小时前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
雨白9 小时前
哈希:以时间换空间的算法实战
算法
螺丝钉code9 小时前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
摇滚侠10 小时前
Maven 入门+高深 单一架构案例 54-59
java·架构·maven·intellij-idea
VidDown11 小时前
Webhook 调试器:让第三方回调“原形毕露”
java·开发语言·javascript·编辑器·postman
San813_LDD11 小时前
[数据结构]LeetCode学习
数据结构·算法·图论