package sort;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @description 插入排序在排序过程中是局部有序,随着插入项的增多,有序部分的项的位置会发生改变
* @author Y
*
*/
public class InsertSort {
public static void main(String[] args) {
int[] a= new int[]{12,73,45,69,35};
sort(a);
System.out.println(a.length);
for (int i : a) {
System.out.println(i + "--");
}
int[] array={12,73,45,69,35};
int i,j,temp;
for(i=1;i<array.length;i++) {
/*
* 第一个for循环
* 把数组分成两部分,右边为未排序,左边为已排序
* 记录排序与未排序分割点temp(temp为下一个排序对象)
*/
temp=array[i];
for(j=i-1;j>=0;j--) {
/*
* 第二个for循环
* 将排序对象temp与已排序数组比较
* 当temp比最近左边的数大时(按从小到大循序排列时)
* 直接结束本次循环,进行下一个数排序
* 否则比左边这个数小时将这个数后移,腾出这个数的位置
*/
if (temp > array[j]) {
break;
}else{
array[j+1] = array[j];//移动
}
}
array[j+1]=temp;
}
System.out.println(Arrays.toString(array));
}
private static void sort(int[] a) {
// TODO Auto-generated method stub
int temp=0;
for (int i = 1; i < a.length; i++) {
temp = a[i];
for (int j = i-1; j>=0; j--) {
if (temp>a[j]) {
break;
}else {
a[j+1] = a[j];//1
a[j] = temp;//2 1+2的操作就是换值
}
}
}
}
}
这里有两种实现了两种插入排序,我们对比一下可以发现,在main里面的插入排序明显是更加优秀的,他化了交换数值的过程。
在sort中,就是每次内层循环的整理过程中
sort里面是每次都比较,完后就换值
在main里面那个版本,就是每次比较完就移动,最后把temp放入数组里