您的位置:首页 > 其它

插入排序

2017-01-08 10:24 375 查看
插入排序应该是最简单的排序,其原理将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2),是稳定的排序方法。

插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。

给定数组A=(5,2,4,6,1,3),其排序过程如下:



Java代码:

public class InsertionSorter {
private InsertionSorter() {}

public static void sort(int[] a) {
sort(a, 0, a.length);
}

public static void sort(int[] a, int fromIndex, int toIndex) {
for (int j = fromIndex + 1; j < toIndex; j++) {
int key = a[j];
// insert a[j] to array a[0..j-1]
int i = j - 1;
while (i >= 0 && a[i] > key) {
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
}
}

public static void sort(Object[] a) {
sort(a, 0, a.length);
}

@SuppressWarnings("unchecked")
public static void sort(Object[] a, int fromIndex, int toIndex) {
for (int j = fromIndex + 1; j < toIndex; j++) {
Object key = a[j];
int i = j - 1;
while (i >= 0 && ((Comparable)a[i]).compareTo(key) > 0) {
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
}
}

public static <T> void sort(T[] a, Comparator<? super T> c) {
sort(a, 0, a.length, c);
}

public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) {
for (int j = fromIndex + 1; j < toIndex; j++) {
T key = a[j];
int i = j - 1;
while (i >= 0 && c.compare(a[i], key) > 0) {
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
}
}

public static void main(String[] args) {
int[] a = {3, 2, 5, 1};
sort(a);
System.out.println(Arrays.toString(a));

Integer[] a2 = {3, 2, 5, 1};
sort(a2);
System.out.println(Arrays.toString(a2));

a2 = new Integer[]{3, 2, 5, 1};
sort(a2, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
System.out.println(Arrays.toString(a2));
}
}


注:代码来自算法导论的Java实现
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  插入排序 算法