Insertion Sort的原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到对应位置然后插入。我不太理解这玩意。。。。不过Arrays.sort(Int[] ints)方法中数组长度小于47时,使用的就是插入算法。
算法描述:
一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
- 从第一个元素开始,该元素可以认为已经被排序;
- 取出下一个元素,在已经排序的元素序列中从后向前扫描;
- 如果该元素(已排序)大于新元素,将该元素移到下一位置;
- 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
- 将新元素插入到该位置后;
- 重复步骤2~5。
package com.ldy.arithmetic.sort;
import java.lang.reflect.Array;
import java.util.Arrays;
public class InsertionSort {
public static void main(String[] args) {
String[] strings={"f","c","a","i","b","d","e","g","h","d"};
int[] ints={19,9,2,3,6,5,4,7,5,11};
// Arrays.sort(ints);
// BubbleSortForString(strings);
BubbleSortForInt(ints);
System.out.println(Arrays.toString(ints));
}
private static void BubbleSortForString(String[] strings) {
int preIndex=0;
String current=null;
for(int cycle=1;cycle<strings.length;cycle++){
preIndex=cycle-1;
current=strings[cycle];
while(preIndex>=0 && current.compareTo(strings[preIndex])<0){
strings[preIndex+1]=strings[preIndex];
preIndex--;
}
strings[preIndex+1]=current;
System.out.println("第"+cycle+"次排序结果为:"+Arrays.toString(strings));
}
}
private static void BubbleSortForInt(int[] ints) {
int preIndex=0;
int current=0;
for(int cycle=1;cycle<ints.length;cycle++){
preIndex=cycle-1;
current=ints[cycle];
while (preIndex>=0 && current<ints[preIndex]){
ints[preIndex+1]=ints[preIndex];
preIndex--;
}
ints[preIndex+1]=current;
System.out.println("第"+cycle+"次排序结果为:"+Arrays.toString(ints));
}
}
}
结果输出:先对比队列中的前两位完成排序。第三位的指与已排序的前两位进行对比,找到位置完成插入。