zoukankan      html  css  js  c++  java
  • 插入排序

    插入排序常用的两种实现方法有直接插入排序,希尔排序。

    有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法——插入排序法

    NO.1 直接插入排序

    void InsertSort(int a[], int n) {
      for (int i = 1; i < n; i++) {
        if (a[i] < a[i-1]) {//若第i个元素大于i-1,直接插入,反之则移动有序表后插入 
          int j = i-1;
          int temp = a[i];//复制为哨兵,即存储待排序元素 
          while ( j >= 0 && temp < a[j]) {//查找在有序表的插入位置 
            a[j+1] = a[j];
            j--;//元素后移 
          }
          a[j+1] = temp;//插入到正确位置 
        }
      }
    }

    NO.2 希尔排序

    和直接插入排序不同的是,希尔排序利用增量,对两个间隔为增量长度的数据进行直接插入排序。

    void ShellInsertSort(int a[], int n, int flag) {
      for (int i = flag; i < n; i++) {
        if (a[i] < a[i-flag]) {//若第i个元素大于i-1,直接插入,反之则移动有序表后插入 
          int j = i-flag;
          int temp = a[i];//复制为哨兵,即存储待排序元素 
          while (j >= 0 && temp < a[j]) {//查找在有序表的插入位置 
            a[j+flag] = a[j];
            j -= flag;//元素后移 
          }
          a[j+flag] = temp;//插入到正确位置 
        }
      }
    }
    void ShellSort(int a[], int n) {
      int flag = n / 2;//初始增量为数组长度的一半 
      while (flag >= 1) {
        ShellInsertSort(a, n, flag);
        flag /= 2;//增量减小为一半 
      }
    }
  • 相关阅读:
    leetcode74
    leetcode59
    leetcode1283
    0079. Word Search (M)
    0067. Add Binary (E)
    0203. Remove Linked List Elements (E)
    用async 解放你的大脑
    Python 类属性和方法
    Python 类装饰器
    Python 装饰器
  • 原文地址:https://www.cnblogs.com/Rhett-Q/p/5483548.html
Copyright © 2011-2022 走看看