1、基本实现
/**
*实现插入排序
*方法一
*O(n^2)
*/
public class InsertSort {
public void insertSort(int[]arr,int n) {
for(int i=1;i<n;i++) {
for(int j=i;j>0;j--) {
if(arr[j]<arr[j-1])
swap(arr,j,j-1);
}
}
}
private void swap(int[] arr, int i, int j) {
if(i!=j) {
int temp =arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
2、优化实现
/**
*实现插入排序
*方法二
*主要优化了内层循环,可以提前结束,且不使用swap方法,
*因为一次交换相当于三次赋值加上索引数组变量
*先复制最后交换
*O(n^2)
*/
public class InsertSort2 {
public void insertSort2(int[]arr,int n) {
for(int i=1;i<n;i++) {
int temp=arr[i];//先把当前变量复制
int j;
for(j=i;j>0&&temp<arr[j-1];j--) {//j的左边已经排好序
arr[j]=arr[j-1];
}
arr[j]=temp;
}
}
}