插入排序算法的简单实现

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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章