package sun;
public class Sort {
/**
*
* @param a 待排序数组
*/
public static void insertSort(int[] a){
int i , j;
int temp;
//第一个元素有序,从第二个开始比较
for(i = 1;i <= a.length-1;i++){
temp = a[i];
j = i-1;
//待排序元素比前面的小,则前面的数组向后移动,j指针继续向前
while(j >= 0 && temp < a[j]){
a[j+1] = a[j];
--j;
}
//j指针确定最后待排元素的位置
a[j+1] = temp;
}
}
public static void main(String[] args) {
int[] arr = {49,38,65,97,76,13,27,49};
insertSort(arr);
for(int a : arr)
System.out.println(a);
}
}
直接插入排序
最新推荐文章于 2024-12-13 15:13:27 发布