直接排序的基本思想是每趟将一条待排记录,按其关键字值的大小插入到前面已经排好序的记录序列中,直到全部记录插入完成位置。
1.示例
序列: 8 6 2 4 5 7 1 3
2.代码
public class Test {
//直接插入算法
public void insertSort(int a[], int n)
{
for(int i=1; i<n; i++)
{
int key=a[i];
int j=i-1;
while(j>=0 && key<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1]=key;
}
}
public static void main(String[] args)
{
int[] a={ 8, 6, 2, 4, 5, 7, 1, 3 };
Test test=new Test();
test.insertSort(a, a.length);
System.out.print("排序后: ");
for(int i=0; i<a.length; i++)
System.out.print(a[i]+" ");
System.out.println();
}
}
运行结果:
完成,加油!(凡星逝水2018)