插入法(Java语言)

来源:互联网 发布:暖气片种类知乎 编辑:程序博客网 时间:2024/06/11 18:20
  1. public class Insert {
  2.     public void sort(int[] r) {
  3.         for (int i = 1; i < r.length; i++) {
  4.             int c = r[i];
  5.             int j = i - 1;
  6.             while (j >= 0 && r[j] > c) {
  7.                 r[j + 1] = r[j];
  8.                 j--;
  9.             }
  10.             r[j + 1] = c;
  11.         }
  12.         for (int n = 0; n < r.length; n++) {
  13.             System.out.print(r[n] + ",");
  14.         }
  15.     }
  16.     public static void main(String[] args) {
  17.         int[] values = { 3, 1, 6, 2, 9, 0, 7, 4, 5 };
  18.         Insert cbean = new Insert();
  19.         cbean.sort(values);
  20.     }
  21. }
插入算法在数据规模小的时候十分高效,该算法每次插入第K+1到前K个有序数组中一个合适位置,K从0开始到N-1,从而完成排序。
原创粉丝点击