ITPub博客

首页 > IT职业 > IT职场 > Java排序算法之冒泡排序

Java排序算法之冒泡排序

IT职场 作者:piny 时间:2021-09-09 09:49:39 0 删除 编辑

         

package com.xingej.algorithm.sort.bubble;/** * 自定义数组类 *  * 特点是:带有冒泡排序功能 *  * 冒泡排序核心:1、从数组的最后一个元素,开始比较;2、两两比较,满足条件的话,就需要进行位置的互换 *  * 实际生活中:小学时,需要根据身高进行座位排序,就可以使用冒泡排序进行。 *  * @author erjun 2017年12月11日 上午9:20:28 */public class MyArrayWithBubbleSort {    // 声明一个数组    private int[] arr;    // 数组,最多能存储多少个元素    private int maxSize;    // 当前数组里,有多少个元素;有点类似于指针,索引的意思    private int elements;    public MyArrayWithBubbleSort(int maxSize) {        this.maxSize = maxSize;        arr = new int[maxSize];        // 初始化状态,数组里的默认元素个数为0        this.elements = 0;    }    public void insert(int value) {        arr[elements++] = value;    }    public void show() {        for (int i = 0; i  i; j--) {                // 后面的/下面的水泡 小于 上面的水泡,就移位                if (arr[j] 


单元测试:

package com.xingej.algorithm.sort.bubble;import org.junit.Test;public class MyArrayWithBubbleSortTest {    @Test    public void test() {        MyArrayWithBubbleSort bubbleSort = new MyArrayWithBubbleSort(6);        bubbleSort.insert(2);        bubbleSort.insert(3);        bubbleSort.insert(1);        bubbleSort.insert(7);        System.out.println("------排序前----打印输出------");        bubbleSort.show();        bubbleSort.bubbleSort();        System.out.println("------排序后----打印输出------");        bubbleSort.show();    }}


代码已托管到

https://github.com/xej520/xingej-algorithm





来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3034/viewspace-2813053/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2020-05-13

  • 博文量
    137
  • 访问量
    8808