对欲排序的元素以插入的方式寻找该元素适当的位置,以达到排序的目的
说明:
- 开始有一个无序表和一个有序表
- n个元素,其中1个元素在有序表,n-1个元素在无序表
- 每次从无序表取出第一个元素,依次与有序表进行比较,插入到合适位置,形成新的有序表
public class InsertSort {
public static void main(String[] args) {
int arr[] = {10, 50, 3, 7, 14};
int len = arr.length;
for(int i = 1;i <= len -1 ;i++) {
int j = i;
int InsertValue = arr[i];
int InsertIndex = i - 1;
while (InsertIndex >= 0 && InsertValue < arr[InsertIndex]) {
arr[InsertIndex+1] = arr[InsertIndex];
InsertIndex--;
}
if(InsertIndex+1 != i) {
arr[InsertIndex + 1] = InsertValue;
}
}
System.out.println(Arrays.toString(arr));
}
}