您的位置:首页 > 其它

直接插入排序

2016-04-24 11:11 246 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: