插入排序
一、插入排序法介绍
插入式排序属于内部排序法,是对于欲排序的元素以插入的方式找寻该元素的适当位置,以达到排序的目的。
二、插入排序法思想
插入排序(Insertion Sorting)的基本思想是:把n个待排序的元素看成为一个有序表和一个无序表,开始时有序表中只包含一个元素,无序表中包含有n-1个元素,排序过程中每次从无序表中取出第一个元素,把它的排序码依次与有序表元素的排序码进行比较,将它插入到有序表中的适当位置,使之成为新的有序表。
三、插入排序图解
四、插入排序优化
将待排序的元素与有序部分的元素比较时,不再挨个比较,而是用二分折中的方式进行比较,加快比较效率。
五、源码
/**
* @author(作者):Liubaoteng
* @date(创建日期):2022/7/27 15:38
* 插入排序
* *****************************************************************************
*/
public class InsertSort {
public static void main(String[] args) {
// int arr[] = {3,44,38,5,47,15,36,26,27,2,46,4,19,50,48};
// insertSort2(arr);
// System.out.println(Arrays.toString(arr));
int[] arr = new int[80000];
for(int i =0; i < 80000;i++) {
arr[i] = (int)(Math.random() * 8000000); //生成一个[0, 8000000) 数
}
System.out.println("80000条数据排序开始:");
long start1 = System.currentTimeMillis();
// insertSort1(arr);//4061
insertSort2(arr);//901
long end1 = System.currentTimeMillis();
System.out.println("80000条数据排序结束:");
System.out.println("80000条数据排序耗时:"+(end1-start1));
}
/**
*插入排序-简单版
**/
public static void insertSort1(int[] arr){
int temp = 0;
for(int i=1;i<=arr.length-1;i++){
/**
*当前数据arr[i]为待比对的数据
* 要和i-1个索引作比对,直至交换
**/
for(int j = i;j>=1;j--){
if(arr[j] < arr[j-1]){
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
}
/**
*插入排序-优化版 折半插入排序
* 将待排序的元素与有序部分的元素比较时,
* 不再挨个比较,而是用二分折中的方式进行比较,加快比较效率
**/
public static void insertSort2(int[] arr){
int j,low,mid,high,temp;
for(int i = 1;i<arr.length;i++){
low = 0;
high = i-1;
temp = arr[i];
/*找到合适的插入位置high+1,如果中间位置元素
*比要插入元素大,则查找区域向低半区移动,否
*则向高半区移动
*/
while(low <= high){
mid = (low+high)/2;
if(arr[mid]>temp){
high = mid-1;
}else{
low = mid+1;
}
}
/*high+1后的元素后移*/
for(j = i-1;j >= high+1;j--)
{
arr[j+1] = arr[j];
}
/*将元素插入到指定位置*/
arr[j+1] = temp;
}
}
}