定义
插入排序,一般也被称为直接插入排序。对于少量元素的排序,它是一个有效的算法 。插入排序是一种最简单的排序方法,它的基本思想是将一个记录插入到已经排好序的有序表中,从而一个新的、记录数增1的有序表。在其实现过程使用双层循环,外层循环对除了第一个元素之外的所有元素,内层循环对当前元素前面有序表进行待插入位置查找,并进行移动 。
代码实现
public class Main {
static int a[]= {90,74,31,17,14,35,74,29,57,14,72,30,31,22,34,1,82,87,67,43};
static void print(int [] a) {
for(int t:a) {
System.out.print(t+" ");
}
System.out.println();
}
public static void main(String[] args) {
System.out.print("排序前:");
print(a);
Insertion_Sort(a);
System.out.print("排序后:");
print(a);
}
static void Insertion_Sort(int [] a){
for(int i=0;i<a.length;i++) {
int next=i;
int t=a[next];
while(next>0 && t<=a[next-1]) {
a[next]=a[next-1];
next--;
}
a[next]=t;
}
}
}
排序前:90 74 31 17 14 35 74 29 57 14 72 30 31 22 34 1 82 87 67 43
排序后:1 14 14 17 22 29 30 31 31 34 35 43 57 67 72 74 74 82 87 90