Java排序算法之冒泡排序

本文介绍了一个自定义数组类,该类具备冒泡排序功能。通过具体代码实现及单元测试展示了如何创建数组、插入元素并进行排序的过程。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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 < elements; i++) {
             System.out.print(arr[i] +  " " );
         }
 
         System.out.println();
     }
 
     public  void  bubbleSort() {
         // 4 3 2 1,按冒泡排序的话,需要进行3轮比较可以了
         for  ( int  i =  0 ; i < elements -  1 ; i++) {
             // 每一轮比较,找出本轮的最小值
             for  ( int  j = elements -  1 ; j > i; j--) {
 
                 // 后面的/下面的水泡 小于 上面的水泡,就移位
                 if  (arr[j] < arr[j -  1 ]) {
                     swap(j, j -  1 );
                 }
             }
         }
     }
 
     // 左右值交换
     private  void  swap( int  i,  int  j) {
         // java 是引用传递
         int  temp = arr[i];
         arr[i] = arr[j];
         arr[j] = temp;
     }
 
}


单元测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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













本文转自故新51CTO博客,原文链接: http://blog.51cto.com/xingej/2049607,如需转载请自行联系原作者



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值