首页 > 代码库 > 关于冒泡算法

关于冒泡算法

  1. 首先冒泡算法就是每次把最大的找出来,冒泡出去,但是有2种不同实现。

    第一:


  2. public class Test12{
        public static void main(String[] args){/*
            int score[] = {67, 88, 45, 87, 29, 99, 109, 100};
            for (int i = 0; i < score.length -1; i++){    //最多做n-1趟排序
                for(int j = 0 ;j < score.length - i - 1; j++){    //对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的)
                    if(score[j] > score[j + 1]){    //把小的值交换到后面
                        int temp = score[j];
                        score[j] = score[j + 1];
                        score[j + 1] = temp;
                    }
                }            
                System.out.print("第" + (i + 1) + "次排序结果:");
                for(int a = 0; a < score.length; a++){
                    System.out.print(score[a] + "\t");
                }
                System.out.println("");
            }
                System.out.print("最终排序结果   :");
                for(int a = 0; a < score.length; a++){
                    System.out.print(score[a] + "\t");
           }
        */
        	int[] score = {67, 88, 45, 87, 29, 99, 109, 100};	
        	bubblesort(score);
        }
第二种:
//===============冒泡排序---之最=====================================================
    public static void bubblesort(int[] arry){
    	for(int i = 0;i < arry.length-1;i++){
    		for(int j = arry.length-1;j > i;j--){
    			if(arry[j]>arry[j-1]){
    				int temp = arry[j];
    				arry[j] = arry[j-1];
    				arry[j-1] = temp;
    			}
    		}
    		System.out.print("第"+(i+1)+"次排序:");
    		for (int i1 : arry) {
				System.out.print(i1 +" ");
			}
    		System.out.println();
    	}
    }

关于冒泡算法