插入排序算法
插入排序是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
例如:我们需要对{9,0,2,3,8,4,7,5,6,1}进行排序
经过第1次循环,temp=0,比较了1次,结果为[0, 9, 2, 3, 8, 4, 7, 5, 6, 1]
经过第2次循环,temp=2,比较了1次,结果为[0, 2, 9, 3, 8, 4, 7, 5, 6, 1]
经过第3次循环,temp=3,比较了1次,结果为[0, 2, 3, 9, 8, 4, 7, 5, 6, 1]
经过第4次循环,temp=8,比较了1次,结果为[0, 2, 3, 8, 9, 4, 7, 5, 6, 1]
经过第5次循环,temp=4,比较了2次,结果为[0, 2, 3, 4, 8, 9, 7, 5, 6, 1]
经过第6次循环,temp=7,比较了2次,结果为[0, 2, 3, 4, 7, 8, 9, 5, 6, 1]
经过第7次循环,temp=5,比较了3次,结果为[0, 2, 3, 4, 5, 7, 8, 9, 6, 1]
经过第8次循环,temp=6,比较了3次,结果为[0, 2, 3, 4, 5, 6, 7, 8, 9, 1]
经过第9次循环,temp=1,比较了8次,结果为[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
插入排序算法代码如下:
public static void insert(int[] arr){
for(int i = 1;i<arr.length;i++ ){
// 用临时变量 存放我们要插入的数据
int temp = arr[i];
// 存放临时变量的位置
int j;
// 用该临时变量与它之前的作比较,
// 如果前面的数比临时变量大,就往后挪一位
// 直到前面的数比较完或者遇到一个比临时变量小的
for ( j = i; j >0&&arr[j-1]>temp ; j--) {
//tip:SortUtil工具类在文档后面有代码,该方法是交换两数的位置
SortUtil.swap(arr,j,j-1);
}
}
}
在main()方法中调用,测试:
public static void main(String[] args) {
int [] arr = {9,0,2,3,8,4,7,5,6,1};
insert(arr);
System.out.println(Arrays.toString(arr));
}
输出结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
另外我写一个工具类对我们写的算法进行验证,看其正确性
public static void main(String[] args) {
// 传入当前类的.class对象 和 排序方法名 , 会用一个length为1000的随机数组对算法进行检查,
// 数组length可以在SortUtil进行修改
System.out.println(SortUtil.check(Insert.class, "insert"));
}
输出结果:true 代表验证通过
SortUtil类
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Random;
public class SortUtil {
/*
*产生随机数组
*/
public static int[] randomArr(Integer length){
int arr[] =new int[length] ;
Random random = new Random();
for (int i=0;i<length;i++){
int randomNum = random.nextInt(length);
arr[i]=randomNum;
}
return arr;
}
/*
验证器
*/
public static Boolean matcher(int[] arr1,int[] arr2){
for (int i = 0; i < arr1.length ; i++) {
if(arr1[i]!=arr2[i]){
System.out.println(arr2[i]);
System.out.println(arr1[i]);
return false;
}
}
return true;
}
//交换数组中两个数的位置
public static void swap(int[] arr,int i,int j){
// int temp= arr[j];
// arr[j]=arr[i];
// arr[i] = temp;
arr[i]=arr[i]^arr[j];
arr[j]=arr[i]^arr[j];
arr[i]=arr[i]^arr[j];
}
//检查
public static Boolean check(Class sortClass,String sortMethodName) {
try {
//可以修改randonArr()的参数改变随机数组的长度
int arr[] = SortUtil.randomArr(1000);
//拷贝一份用于验证
int[] copy = Arrays.copyOf(arr, arr.length);
// 用自己实现的算法排序
Method sort = sortClass.getMethod(sortMethodName, int[].class);
sort.invoke(arr.getClass(),arr);
//用arrays工具类对复制的数组排序
Arrays.sort(copy);
//返回结果
return SortUtil.matcher(copy, arr);
}catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e){
e.printStackTrace();
return false;
}
}
}
项目github地址:https://github.com/codecwf/algorithm.git 欢迎下载,也请大家多多指教