欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java插入排序,

来源: javaer 分享于  点击 45544 次 点评:9

Java插入排序,


插入排序:

通常人们整理桥牌的方法是一张一张的来,将每一张牌插入到其他已经有序的牌中的适当位置。在计算机的实现中,为了给要插入的元素腾空间,我们需要将其余所有元素在插入之前都向右移动一位。

package sortTest;

/**
 * Created by Main on 2018/5/8.
 */
public class InsertSort {

    public static boolean less(Comparable a,Comparable b){
        return a.compareTo(b)<0;
    }

    public static void exchange(Comparable[] a,int i,int j){
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    public static void insertSort(Comparable[] a){
        for (int i = 0; i < a.length; i++) {
            for (int j = i; j >0 ; j--) {
                if(less(a[j],a[j-1])){
                    exchange(a,j,j-1);
                }
            }
        }
    }

    public static void main(String[] args) {
        Integer[] numbers = new Integer[]{1,8,9,2,6,5,7};
        insertSort(numbers);
        for (Integer number: numbers) {
            System.out.print(number);
        }
    }

}

相关文章

    暂无相关文章
相关栏目:

用户点评