算法思想(从小到大排序)
- 将待排序数组看左右两个序列,左序列有序,有序列无序。
- 假设第一个数array[0]为有序列,那么array[1,N-1]为无序列.循环遍历无序列,找出array[i]在有序列中应该插入的位置,插入。
- 例如一个乱序数组为{1,3,2,4 , 假如有序列为 { 1,3 } 无序列循环到2时 ,那么2在有序列中的位置应该是1 - 3 中间 , 所以 [ 3. . .2 ) 之间的所有数据右移 , 即3右移的2的位置 , 腾出了3原先所在的位置 , 由2替代
博客地址:http://blog.youkuaiyun.com/mkrcpp/article/details/39320797
import java.util.Arrays;
/***
* @title 直接插入排序
* @author michael.mao
* @date 2014年9月16日 下午1:59:04
* @version V1.0
*/
public class InsertSort
{
/***
* @title 直接插入排序
* @description 将待排序数组看左右两个序列,左序列有序,有序列无序。
* 假设第一个数array[0]为有序列,那么array[1,N-1]为无序列.循环遍历无序列,找出array[i]
* 在有序列中应该插入的位置,插入。<br/>
* 例如一个乱序数组为{1,3,2,4 , 假如有序列为 { 1,3 } 无序列循环到2时 ,
* 那么2在有序列中的位置应该是1 - 3 中间 , 所以 [ 3. . .2 ) 之间的所有数据右移 , 即3
* 右移的2的位置 , 腾出了3原先所在的位置 , 由2替代
* @author michael.mao
* @date 2014年9月16日 下午2:08:40
* @version V1.0
*/
public static void execute(int[] array)
{
// 待插入的位置
int tmpV, j = 0;
// 循环无序列,次数为 N-1,默认有序列为 {array[0]}
for (int i = 1; i < array.length; i++)
{
// 保存待插入的值
tmpV = array[i];
// 在有序列中找到合适的位置
for (j = 0; j < i; j++)
if ( array[i] < array[j] )
break;
// 如果array[i]比有序列中任何一个都大,则j退出循环时, j == i,则array[0,i]为有序列,无需插入
if ( j != i )
{
// 将[j,i-1]顺序右移,腾出array[j]位置
for (int k = i - 1; k >= j; k--)
array[k + 1] = array[k];
// 插入
array[j] = tmpV;
}
System.err.println(i + "----" + Common.print(array));
}
}
// 循环测试次数
public static int LOOP_COUNT = 1;
public static int ARRAY_SIZE = 7;
public static void main(String[] args)
{
int[] mArray = Common.getArray(ARRAY_SIZE);
int allTime = 0;
for (int i = 0; i < LOOP_COUNT; i++)
{
// 拷贝数组
int[] tmpArray = Arrays.copyOf(mArray, ARRAY_SIZE);
Common.print(tmpArray);
long tmpTime = System.currentTimeMillis();
execute(tmpArray);
Common.print(tmpArray);
allTime += System.currentTimeMillis() - tmpTime;
}
System.err.println("数组大小为(" + ARRAY_SIZE + ")的" + LOOP_COUNT + "次插入排序的平均耗时为:" + allTime / (float) LOOP_COUNT);
}
}
1----58 80 15 27 01 68 43
2----15 58 80 27 01 68 43
3----15 27 58 80 01 68 43
4----01 15 27 58 80 68 43
5----01 15 27 58 68 80 43
6----01 15 27 43 58 68 80
数组大小为(10000)的100次直接插入排序的平均耗时为:17.58 ms