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