直接插入排序

来源:互联网 发布:金融学什么网络大学好 编辑:程序博客网 时间:2024/06/06 19:20
package sort;/** * 直接插入排序 * (将第一个元素看成有序序列,后面的元素依次插入该序列使之还是一个有序序列) * @author zheng */public class InsertSort {public static void main(String[] args) {int[] arr={12,33,213,43,11,25};//从第二个元素开始循环与之前的有序序列比较for(int i=1;i<arr.length;i++){int data=arr[i];int temp=i;//while循环作用:待插入元素插入到合适位置while(temp>0&&arr[temp-1]>data){arr[temp]=arr[temp-1];temp--;}//交换数据,使之构成有序序列arr[temp]=data;}//打印输出for(int i:arr){System.out.print(i+" ");}}}

原创粉丝点击