直接插入排序算法思想:
将n个待排序的数据分为有序表,无序表。
一开始有序表为一个元素。剩下的无序表为n-1 个元素。
在排序过程中,每次从无序表取出的第一个元素插入有序区合适的位置,使之成为新的有序表,重复n-1次可完成排序过程
步骤
:
(1)取出无序表的第一个元素,并找出它在有序表的对应位置
(2)将无序表的元素插入到有序表,如果有必要的话,有序表的元素进行相关移位
Java代码实现:
class Insert{
public static void insertSort(int a [],int n){
int i,j;
int t; //临时变量
for(i = 1; i < n; i++){
t = a[i];
j = i - 1;
while(j >= 0 && t < a[j]){
a[j + 1] = a[j]; ///元素后移,腾出位置插入t
j--;
}
a[j + 1] = t;
}
}
}
public class MyClass {
public static void main(String[] args) {
int i;
int a [] = new int []{1,2,34,33,5,4,44,89,65};
System.out.print("排序前");
for(int b:a){
System.out.print(b + ",");
}
Insert.insertSort(a,a.length);
System.out.println();
System.out.print("排序后");
for(int c:a){
System.out.print(c + ",");
}
}
}
结果: