基于JAVA的排序算法之一--冒泡排序

各种排序算法:冒择路(入)兮(稀)快归堆,桶式排序,基数排序

冒泡排序,选择排序,插入排序,稀尔排序,快速排序,归并排序,堆排序,桶式排序,基数排序

一、冒泡排序(BubbleSort)

1. 基本思想:

  两两比较待排序数据元素的大小,发现两个数据元素的次序相反时即进行交换,直到没有反序的数据元素为止。

2. 排序过程:

  设想被排序的数组R[1..N]垂直竖立,将每个数据元素看作有重量的气泡,根据轻气泡不能在重气泡之下的原则,从下往上扫描数组R,凡扫描到违反本原则的轻气泡,就使其向上"漂浮",如此反复进行,直至最后任何两个气泡都是轻者在上,重者在下为止。

【示例】:

49 13 13 13 13 13 13 13

38 49 27 27 27 27 27 27

65 38 49 38 38 38 38 38

97 65 38 49 49 49 49 49

76 97 65 49 49 49 49 49

13 76 97 65 65 65 65 65

27 27 76 97 76 76 76 76

49 49 49 76 97 97 97 97

java代码实现:

   

04.   

05.public class BubbleSort {      

06.     

07.         

14.    public void bubble(Integer[] array, int from, int end) {      

15.        //需array.length - 1轮比较      

16.        for (int k = 1; k < end - from + 1; k++) {      

17.            //每轮循环中从最后一个元素开始向前起泡,直到i=k止,即i等于轮次止      

18.            for (int i = end - from; i >= k; i--) {      

19.                //按照一种规则(后面元素不能小于前面元素)排序      

20.                if ((array[i].compareTo(array[i - 1])) < 0) {      

21.                    //如果后面元素小于了(当然是大于还是小于要看比较器实现了)前面的元素,则前后交换      

22.                    swap(array, i, i - 1);      

23.                    

24.                

25.            

26.        

27.       

28.         

34.    public void swap(Integer[] array, int i, int j) {      

35.        if (i != j) {//只有不是同一位置时才需交换      

36.            Integer tmp = array[i];      

37.            array[i] = array[j];      

38.            array[j] = tmp;      

39.            

40.        

41.   

42.       

43.         

47.    public static void main(String[] args) {      

48.        Integer[] intgArr = { 7, 2, 4, 3, 12, 1, 9, 6, 8, 5, 11, 10 };      

49.        BubbleSort bubblesort = new BubbleSort();      

50.        bubblesort.bubble(intgArr,0,intgArr.length-1);   

51.        for(Integer intObj:intgArr){   

52.            System.out.print(intObj + " ");   

53.         

54.        

55.}     



另外一种实现方式:

 

public class BubbleSort2{ 

    public static void main(String[] args){ 

        int[] a = {3,5,9,4,7,8,6,1,2}; 

        BubbleSort2 bubble = new BubbleSort2(); 

        bubble.bubble(a); 

        for(int num:a){ 

            System.out.print(num + " "); 

       

   

     

    public void bubble(int[] a){ 

        for(int i=a.length-1;i>0;i--){ 

            for(int j=0;j<i;j++){ 

                if(new Integer(a[j]).compareTo(new Integer(a[j+1]))>0){ 

                    swap(a,j,j+1); 

               

           

       

   

    public void swap(int[] a,int x,int y){ 

        int temp; 

        temp=a[x]; 

        a[x]=a[y]; 

        a[y]=temp; 

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值