插入排序

来源:互联网 发布:spss 23 for mac 破解 编辑:程序博客网 时间:2024/06/03 18:13

包括直接插入排序,希尔插入 排序

1. 直接插入排序

    1.将一个记录直接插入已经排好的有些表中。    2.从数组的第二个数据开始处理:    a.该数据往前移动之前使用temp变量备份一下。    b.如果temp比它前面的数据要小,说明该数据要往前移动。    c.将前面的数据后移一位。    d.继续往前搜索,如果temp比它前面的数据小重复执行b,c步骤。如果temp比它前面的数据大,则找到插入位置。    e.把temp的值放入该位置。    3.执行下一趟排序。直到数组最后一个排完为止。

这里写图片描述

public class 直接插入排序 {    public static void main(String[] args) {        int [] arr={3,6,4,2,11,10,5};        int index=0;        //第一个数肯定是有序的        for (int i = 1; i < arr.length; i++) {             int j = 0;             int temp = arr[i]; // 取出第i个数,和前i-1个数比较后,插入合适位置       // 因为前i-1个数都是从小到大的有序序列,所以只要当前比较的数(list[j])比temp大,就把这个数后移一位             for (j = i - 1; j >= 0 && temp < arr[j]; j--) {                  arr[j+1] = arr[j];              }              arr[j + 1] = temp;        }        for (int i = 0; i < arr.length; i++) {            System.out.println(arr[i]+ "");        }    }}

2.希尔插入 排序

又称缩小增量排序。
先将排序序列分成若干个子序列,分别进行直接插入排序,带整个序列基本有序,再对全体序列进行一次直接插入排序。
传送门

public class ShellSortTest {      public static int count = 0;      public static void main(String[] args) {          int[] data = new int[] { 5, 3, 6, 2, 1, 9, 4, 8, 7 };          print(data);          shellSort(data);          print(data);      }      public static void shellSort(int[] data) {          // 计算出最大的h值          int h = 1;          while (h <= data.length / 3) {              h = h * 3 + 1;          }          while (h > 0) {              for (int i = h; i < data.length; i += h) {                  if (data[i] < data[i - h]) {                      int tmp = data[i];                      int j = i - h;                      while (j >= 0 && data[j] > tmp) {                          data[j + h] = data[j];                          j -= h;                      }                      data[j + h] = tmp;                      print(data);                  }              }              // 计算出下一个h值              h = (h - 1) / 3;          }      }      public static void print(int[] data) {          for (int i = 0; i < data.length; i++) {              System.out.print(data[i] + "\t");          }          System.out.println();      }  }  
0 0
原创粉丝点击