• 插入排序


    #include"iostream"
    #include"time.h"
    using namespace std;
    void show(int *a,int N){
        for(int i = 0;i < N;i++){
            cout<< a[i]<<ends;
        }
        cout<<endl;
    }
    //直接插入排序
    void sort(int *a,int n){
        for(int i = 0;i < n;i++){        //依次取出i往前插入
            int temp = a[i];            //保存i
            for(int j = i - 1;j >= 0 && temp < a[j];j--){        //找到插入点j
                a[j + 1] = a[j];        //比i大的元素往后移,给i腾位置,直到j等于0或者i>j,则找到插入点
            }
            a[j + 1] = temp;            //将i插入腾出的位置
        }
    }
    //二分插入排序
    void sortbin(int *a,int n){
        for(int i = 0;i < n;i++){
            int temp = a[i];
            int low = 0,high = i - 1;
            while(low <= high){
                int mid = (low + high) / 2;
                if(a[mid] < temp){
                    low = mid + 1;
                }
                else{
                    high = mid - 1;
                }
            }
            //这里low或者high-1都为插入点
            for(int j = i - 1;j >= low;j--){
                a[j + 1] = a[j];
            }
            a[low] = temp;
        }
    }
    //希尔排序
    void shellsort(int *a,int n){
        for(int shell = n / 2;shell > 0 ;shell /= 2){
            //插入排序
            for(int i = shell;i < n;i++){
                int temp = a[i];
                for(int j = i - shell;j >= 0 && temp < a[j];j -= shell){
                    a[j + shell] = a[j];
                }
                a[j + shell] = temp;
            }
        }
    }
    
    int main(){
        srand(time(NULL));
        const int N = 10;
        int a[N];
        for(int i = 0;i < N;i++){
            a[i] = rand() % 10;
        }
        show(a,N);
        shellsort(a,N);
        show(a,N);
        return 0;
    }
  • 相关阅读:
    wait与sleep区别?
    oracle死锁查询
    atomic 原子操作的类
    买票问题
    0001.第一个多线程demo--分批处理数据
    01: JavaScript实例
    01: 运维工作梳理
    04: 使用BeautifulSoup封装的xss过滤模块
    04: 打开tornado源码剖析处理过程
    03: 自定义异步非阻塞tornado框架
  • 原文地址:https://www.cnblogs.com/oleolema/p/9074807.html
Copyright © 2020-2023  润新知