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); } }