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

    #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;
    }
  • 相关阅读:
    linux —— 学习笔记(汇总)
    linux —— ubuntu 初次安装问题
    更改CMD默认的初始路径
    深入浅出理解linux inode结构
    重拾简单的linux指令之info 【转】
    Python 中数据的序列化和反序列化(json处理)
    day07
    Python 的反射机制
    Python 的 __new__()方法与实例化
    Classes as objects
  • 原文地址:https://www.cnblogs.com/oleolema/p/9074807.html
Copyright © 2011-2022 走看看