ecord the new
* vacancy as j
*/
array[j + 1] = array[j];
vacancy = j;
}
}
// set the sentry to the new vacancy
array[vacancy] = sentry;
}
}
}
}
/**
* Sort the array of generic T with insertion sort order
*
* @param array
* the array of generic
*/
public
> void doSortT(T[] array) {
if (array != null && array.length > 0) {
int length = array.length;
for (int i = 1; i < length; i++) {
if (array[i].compareTo(array[i - 1]) < 0) {
T sentry = array[i];
int vacancy = i;
for (int j = i - 1; j >= 0; j--) {
if (array[j].compareTo(sentry) > 0) {
array[j + 1] = array[j];
vacancy = j;
}
}
array[vacancy] = sentry;
}
}
}
}
}
测试TestInsertionSortord:
package com.meritit.sortord.insertion;
import java.util.Arrays;
/**
* Test insertion sort order
*
* @author ysjian
* @version 1.0
* @email ysjian_pingcx@126.com
* @QQ 646633781
* @telephone 18192235667
* @csdnBlog http://blog.csdn.net/ysjian_pingcx
* @createTime 2013-12-31
* @copyRight Merit
*/
public class TestInsertionSortord {
public static void main(String[] args) {
InsertionSortord insertSort = InsertionSortord.getInstance();
int[] array = { 3, 5, 4, 2, 6 };
System.out.println(Arrays.toString(array));
insertSort.doSort(array);
System.out.println(Arrays.toString(array));
System.out.println("---------------");
Integer[] array1 = { 3, 5, 4, 2, 6 };
System.out.println(Arrays.toString(array1));
insertSort.doSortT(array1);
System.out.println(Arrays.toString(array1));
}
}
直接插入排序算法详解:http://blog.csdn.net/ysjian_pingcx/article/details/8674454 直接插入算法源码免积分下载:http://download.csdn.net/detail/ysjian_pingcx/6802851