首页 > 代码库 > 冒泡算法

冒泡算法

public class BubbleSortTest {
    public static void main(String[] args) {
        int[] A=new int[]{5,6,7,9,8,1,5,3};
        sortIntegers2(A);
        System.out.println(Arrays.toString(A));
    }
    public static void sortIntegers2(int[] A) {
        int flag =1;
        for(int i=0;i<(A.length-1)*flag;i++){
            flag =0;
           for(int j=0;j<A.length-1-i;j++){
               if(A[j]>A[j+1]){
                   int temp =A[j];
                   A[j] =A[j+1];
                   A[j+1] =temp;
                   flag =1;
               }
           }
        }
    }
}

 reverse-pairs

public class ReversePairsTest {
    public static void main(String[] args) {
        int[] A=new int[]{2, 4, 1, 3, 5};
        List<Par> list =reversePairs(A);
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            Par par = (Par) iterator.next();
             System.out.println("("+par.getA1()+","+par.getB1()+")");
        }
    }
    public static List<Par> reversePairs(int[] A) {
       List<Par> list =new ArrayList<Par>();
       for (int i = 0; i < A.length-1; i++) {
           for (int j = 0; j < A.length-1-i; j++) {
               if( A[j] > A[A.length-1-i]){
                   Par par=new ReversePairsTest().new Par();
                   par.setA1(A[j]);
                   par.setB1(A[A.length-1-i]);
                   list.add(par);
                }
           }
      }
       return list;
    }
    
    public class Par{
         private Integer a1;
         private Integer b1;
        public Integer getA1() {
            return a1;
        }
        public void setA1(Integer a1) {
            this.a1 = a1;
        }
        public Integer getB1() {
            return b1;
        }
        public void setB1(Integer b1) {
            this.b1 = b1;
        }
        
    }
}

 

冒泡算法