冒泡排序与选择排序

简单冒泡排序:

package 数组排序_冒泡排序;

/**
 * 冒泡排序算法
 * 
 * @author SeeClanUkyo int类型的数组: 3 1 6 2 5
 */
public class BubbleSort {

    public static void main(String[] args) {

        int[] a = { 3, 1, 6, 2, 5 };

        // 开始排序
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length-1-i; j++) {
                if (a[j] > a[j + 1]) {
                    // 如果左边大,就跟右边交换位置
                    int temp;
                    temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
//                    //使用异或交换两个int类型的数值
//                    a[j] = a[j]^a[j+1]; //
//                    a[j+1] = a[j]^a[j+1];
//                    a[j] = a[j]^a[j+1];
                    
                }
            }
        }
        
        for(int x : a) {
            System.out.print(x+" ");
        }

    }

}

/*
原:3,1,6,2,5

31625
第一次循环:
1,3,6,2,5
1,3,6,2,5
1,3,2,6,5
1,3,2,5,6


1325
第二次循环:
1,3,2,5
1,2,3,5
1,2,3,5


123
第三次循环:
1,2,3
1,2,3


12
第四次循环:
1,2




*/

简单选择排序:

package 数组排序_选择排序;
/**
 * 选择排序
 * @author SeeClanUkyo
 *
 */
public class SelectSort3 {

    public static void main(String[] args) {

        int[] b = {60,90,100,30,97};
        
        int[] selectB = getSelectArray(b);
        
        for(int x : selectB) {
            System.out.print(x+" ");
        }
    }
    
    public static int[] getSelectArray(int[] b) {
        
        //shake with array b
        for(int i=0;i<b.length-1;i++) {
            for(int j=i+1;j<b.length;j++) {
                if (b[i] > b[j]) {
                    int tempInt = b[j];
                    b[j] = b[i];
                    b[i] = tempInt;
                }
            }
        }
        
        return b;
    }

}

 

posted @ 2018-06-13 13:58  ukyo--君君小时候  阅读(139)  评论(0编辑  收藏  举报