Java插入排序类
直接插入排序类似于玩牌时整理手中纸牌的过程。
基本思想:
依次将待排序序列中的每一个记录插入到已排好序的序列中,直到全部记录都排好序。
- 如何初始化有序序列?
对于记录序列{1,5,6,7,4,3,2,8,9}
初始化有序序列{1} 无序序列{5,6,7,4,3,2,8,9}
将data[0]看作有序区
- 如何查找待插入记录的插入位置?
t=data[i]此时手中抓的第i张牌与data[0]~data[i-1]张牌比较,比它大的牌后移,直到某张牌data[j]比它小或者全部比完j=-1时,此时便找到这张牌t该放的位置是j+1,就插入牌t,t=data[j+1]。
一趟插一张,初始化序列不算,总计len-1趟。
编写成类
package test;
public class InsertSort {
/**
* The {@code InsertSort} class for solving the sorting of a set of integers
* @author GU
* @param a
*/
public static void InsertSort(int []a)
{
int len=a.length;
int j;
for(int i=1;i<len;i++)//趟数
{
int t=a[i];//当前手中抓的牌
for( j=i-1;a[j]>t&&j>=0;j--)//手中已排好的牌若比这张牌大后移
a[j+1]=a[j];
a[j+1]=t;//插入空出的位置
}
for(int i=0;i<len;i++)
System.out.print(a[i]+" ");
}
/**
* Unit test for the methods of the {@code InsertSort} class
* @param args
*/
public static void main(String []args)
{
int []a={1,5,6,7,4,3,2,8,9};
InsertSort(a);
}
}
欢迎批评指正!