直接插入排序(java实现)

来源:互联网 发布:c语言自学入门书籍推荐 编辑:程序博客网 时间:2024/05/16 07:55
/** * 在要排序的一组数中,假设前面(n-1)[n>=2] 个数已经是排 *好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数 *也是排好顺序的。如此反复循环,直到全部排好顺序。 *  @author liuxiaoming * */public class InsertSort {public int[] insertSort(int[] sortArray){int temp;//这里从第二个数据开始进行比较,遍历i-1个数据for(int i = 1;i < sortArray.length;i++){    //保存这个要进行插入的数据temp = sortArray[i];int j = i - 1;//将这个插入的数据与前i-1个数据进行比较for(;j >= 0&&sortArray[j] > temp;j--){//将比要插入的数据大的数据集体的像后移动一位sortArray[j+1] = sortArray[j];}//将这个要插入的数据插入到当前的空的位置sortArray[j+1] = temp;}return sortArray;}public static void main(String[] args) {int[] a = {1,3,5,10,9,6,7,8,4,2};int[] result = new InsertSort().insertSort(a);for(int i = 0;i < result.length;i++){System.out.println(result[i]);}}}

原创粉丝点击