代码实现:
package com.datastruct.sort; import java.util.Arrays; /** * 插入排序Java实现 * @author Administrator * */ public class InsertSort { public static void insertSort(int [] array) { for(int i = 1;i<array.length;i++) { int currentIndex = i-1; int currentValue = array[i]; //开始循环移动 while(currentIndex>=0&¤tValue<=array[currentIndex]) { array[currentIndex+1] = array[currentIndex]; currentIndex--; } array[currentIndex+1] = currentValue; } } public static void main(String[] args) { int [] arr = {101,34,228,-1,3}; insertSort(arr); System.out.println(Arrays.toString(arr)); } }
运行的程序结果:
[-1, 3, 34, 101, 228]