1.使用交换排序:
package chapter7;
public class Demo1 {
public static void main(String[] args) {
Integer a[] = { 34, 8, 64, 51, 32, 21 };
insertionSort(a);
}
public static <Integer extends Comparable<? super Integer>> void insertionSort(Integer[] a) {
int j;
for (int i = 1; i < a.length; i++) {
for (j = i; j > 0 && a[j].compareTo(a[j - 1]) < 0; j--) {
Integer temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
2 数据移动排序:
package chapter7;
public class Demo1 {
public static void main(String[] args) {
Integer a[] = { 34, 8, 64, 51, 32, 21 };
insertionSort(a);
}
public static <Integer extends Comparable<? super Integer>> void insertionSort(Integer[] a) {
int j;
for (int i = 1; i < a.length; i++) {
Integer temp = a[i];
for (j = i; j > 0 && temp.compareTo(a[j - 1]) < 0; j--) {
a[j] = a[j - 1];
}
a[j] = temp;
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
插入排序O( N2)