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;//增量减小为一半 
      }
    }
  • 相关阅读:
    剑指offer--2.替换空格
    剑指offer--1.二维数组中的查找
    poj-1426-Find The Multiple(打表水过)
    hdoj-3791-二叉搜索树(二叉搜索树模板题)
    hdoj-1276-士兵队列训练问题(队列模拟)
    HihoCoder
    CodeForces-831A-Unimodal Array (水题)
    hdoj-1046-Gridland(规律题)
    hdoj-1038-Biker's Trip Odometer(水题)
    hdoj-1037-Keep on Truckin'(水题)
  • 原文地址:https://www.cnblogs.com/Rhett-Q/p/5483548.html
Copyright © 2011-2022 走看看