排序

 

 

public class sort{
    public static void main(String[] args) {
        int[] array = {1,5,2,4,9,5,7};
        
        //插入
        for (int i = 1; i < array.length; i++) {
            int currentElement = array[i];
            int k = i -1;
            while (k >= 0 && array[k] > currentElement) {
                array[k + 1] = array[k];
                k --;
            }
            array[k + 1] = currentElement;
        }
        System.out.println(Arrays.toString(array));
        
        //选择
        for (int i = 0; i < array.length-1; i++) {
            int currentMin = array[i];
            int curentMinIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if (currentMin > array[j]) {
                    currentMin = array[j];
                    curentMinIndex = j;
                }
            }
            if (curentMinIndex != i) {
                array[curentMinIndex] = array[i];
                array[i] = currentMin;
            }
        }
        System.out.println(Arrays.toString(array));
        
        //冒泡
        for (int i = 0; i < array.length-1; i++) {
            for (int j = 0; j < array.length-1-i; j++) {
                if (array[j] > array[j+1]) {
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(array));
    }
    
}

 

posted @ 2019-03-12 13:15  ^sun^  阅读(109)  评论(0编辑  收藏  举报