今天介绍的这个排序算法 是比较效率高的排序算法:插入排序
基本思路:每拿到一个元素,都要将这个元素与所有它之前的元素遍历比较一遍,让符合排序顺序的元素挨个移动到当前范围内它最应该出现的位置。
效率:比较和交换次数大致都是N*(N-1)/4,所以这个算法比冒泡大致快一倍,比选择排序略快,尤其是部分数据已经局部有序的情况下,这个算法效率会更高。
具体代码:
package datastrucates.arrays.sort;
/**
* 插入法排序
*
* @author wuxin
*
*/
public class InsertSort {
public static void insertSort(int as[]) {
int j = 0;
for (int i = 0; i < as.length; i++) {
int temp = as[i];
for (j = i; j > 0; j--) {
if (as[j - 1] >= temp) {
as[j] = as[j - 1];
}else {
break;
}
}
as[j] = temp;
}
}
public static void printDatas(int[] as) {
System.out.println("++++++++++++++++++++++++++++");
for (int a : as) {
System.out.println(a);
}
}
public static void main(String[] args) {
int[] as = new int[] { 1, 3, 6, 5, 8 };
printDatas(as);
insertSort(as);
printDatas(as);
}
}
运行结果: