首页 > 代码库 > 插入排序

插入排序

插入排序的关键思想是每次将后端未排序序列的第一个元素插入到前面已经有序的序列中,并且在插入过程中需要与比当前“大”的元素交换位置。插入排序总的交换次数等于原始输入序列的逆序数。简易实现及测试用例如下:

import java.util.logging.Handler;public class Insertion {    private static void exch(Comparable[] a, int i, int j) {        Comparable tmp = a[i];        a[i] = a[j];        a[j] = tmp;    }    private static boolean less(Comparable a, Comparable b) {        return (a.compareTo(b) < 0);    }    private static void show(Comparable[] a) {        int N = a.length;        for (int i = 0; i < N; i++) {            System.out.print(a[i] + " ");        }        System.out.println();    }    public static boolean isSorted(Comparable[] a) {        int N = a.length;        for (int i = 1; i < N; i++) {            if (less(a[i], a[i - 1]))                return false;        }        return true;    }    public static void sort(Comparable[] a) {        int N = a.length;        for (int i = 0; i < N; i++) {            for (int j = i; j > 0 && less(a[j], a[j - 1]); j--) {                exch(a, j, j - 1);            }        }    }    public static void main(String[] args) {        String[] a = StdIn.readAllStrings();        Selection.sort(a);        show(a);    }}
View Code

 

插入排序