排序原理
-
将所有的元素分为两组,已排序的和未排序的
-
找到未排序的元素的第一个,向已排序的组进行插入
-
倒叙已经排序的数组,与待插入的数组进行比较,知道找到小于待插入元素的元素,那么就把此元素放在这,之后的元素后移一位
public class Insertion { public static void sort(Integer[] a) { for (int i =1; i < a.length; i++) { int midindex=i; for (int j = i-1; j >=0; j--) { if(greater(a[j],a[midindex])) { exch(a,midindex,j); midindex--; } } } } //判断两数大小 private static boolean greater(Comparable v,Comparable w) { return v.compareTo(w)>0; } //交换数组a,i处和j处的值 private static void exch(Integer[] b,int i,int j) { int temp; temp=b[i]; b[i]=b[j]; b[j]=temp; } }
import java.util.Arrays; public class test01 { public static void main(String[] args) { Integer[] selection={45,11,0,7,7,-6,78,1,46,-6}; Insertion.sort(selection); System.out.println(Arrays.toString(selection)); } }