美文网首页
插入排序

插入排序

作者: Neymar_ | 来源:发表于2016-10-08 22:25 被阅读0次

优点:对于已经有序或接近有序的数组很快

public class InsertSort {


    private static void insertSort(int[] a) {
        //前n行有序要循环比较n-1次
        for (int x = 1; x < a.length; x++) {
            for (int y = x; y > 0; y--) {
                if (a[y - 1] > a[y]) {
                    int temp = a[y - 1];
                    a[y - 1] = a[y];
                    a[y] = temp;
                    continue;
                }
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {8, 78, 23, 4, 251, 73, 51, 87, 3};
        insertSort(array);
        for (int i : array) {
            System.out.print(i + " ");
        }
    }

}

相关文章

网友评论

      本文标题:插入排序

      本文链接:https://www.haomeiwen.com/subject/cvcpyttx.html