插入排序
- 算法思想: 逐个和前边元素比较,找到比自己小的的元素插入
过程演示
代码实现
public class InsertionSort {
public static void insertSort(int[] array) {
for(int i=1,j=0; i<array.length; i++){
int temp = array[i];
for(j = i-1; j>=0; j--){
if(temp < array[j]){
array[j+1] = array[j];
}
else{
break;
}
}
array[j+1] = temp;
}
}
}
性能分析
稳定性 :稳定
特点 :数据越有序,排序越快
希尔排序
核心思想:分组进行插入排序
过程演示
- 进行希尔排序,首先要选择增量gap=length/2,缩小增量继续以gap = gap/2的方式,这种增量选择可以用一个序列来表示,{n/2,(n/2)/2…1},称为增量序列。希尔排序的增量序列的选择与证明是道数学难题,选择的这个增量序列是比较常用的,也是希尔建议的增量,称为希尔增量。
- 选择好增量之后就根据增量来分组,分组进行插入排序,这样就达到了我们进行插入排序时,数据越有序,效率越快的条件
下图中,每个颜色一样的是一组
代码实现
public class ShellSort {
//直接插入排序
public void shell(int[] array,int gap) {
for (int i = gap,j = 0; i < array.length; i+=gap) {
int temp = array[i];
for (j = i-gap; j >= 0; j -= gap) {
if(temp < array[j]){
array[j+gap] = array[j];
}
else{
break;
}
}
array[j+gap] = temp;
}
}
//分组
public void shellSort(int[] array) {
for (int i = array.length/2; i > 0; i = i/2) {
shell(array,i);
}
}
}
性能分析
稳定性:不稳定