插入排序算法的簡單實現

package com.company;

/**
 * Created by Administrator on 2017/5/1.
 */
 class ArrayUtils {
    public static void printArray(int[] array) {

        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
           if (i< array.length-1)  {
                System.out.print("    ");
            }
        }
        System.out.println("  ");   //輸出數列的各個值,中間有空格。後續頻繁調用
    }  
}
public class Insert {
    public static void insertSort(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        for (int i = 1; i < array.length; i++) {   //具體實現,下標i及其以後的依次加入排序。下標i以前的從小到大依次排好的.
            int currentValue = array[i];  // 每次需要排序的值array[i]


            for (int j = i - 1; j >= 0; j--) {
                if (array[j] > currentValue) {  //每次需要排序的值array[i]與前面的值相比較,如果前面的值大,則替換,否則不動。
                    array[j + 1] = array[j];

                    array[j] = currentValue;  //j值一直變換到第一個數,實現完全比較

                } else {
                    break;
                }
            }
        }
    }
    public static void main(String[] args) {
        int[] array = {5,-4,4,1,8};
        ArrayUtils.printArray(array);
        insertSort(array);
        ArrayUtils.printArray(array);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章