插入排序和希尔排序

插入排序的时间复杂度是O(N^2)
希尔排序的时间复杂度和步长设置有关,如果步长初始为数组总长度的一半,然后每次都取一半,最后的时间复杂度为O(N*logN)
具体的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<assert.h>
#include<map>
#include<vector>
#include<set>
using namespace std;
 
void shell_sort(vector<int>& v){
    int len=v.size();
    len=len/2;
    while(len>=1){
        for(int i=0;i<len;i++){//begin point of insert_sort
            for(int j=i+len;j<v.size();j=j+len)//insert_sort
            {
                int k=j-len;
                int key=v[j];
                while(v[k]>key && k>=0){
                    v[k+len]=v[k];
                    k=k-len;
                }
                v[k+len]=key;
            }//end of insert_sort
        }
        len=len/2;
    }
}
 
void insert_sort(vector<int>& v){
    for(int i=1;i<v.size();i++)
    {
        int j=i-1;
        int key=v[i];
        while(v[j]>key && j>=0){
            v[j+1]=v[j];
            j=j-1;
        }
        v[j+1]=key;
    }
}
 
int main()
{
    int a[]={3,1,2,5,9,10,2,1,4,8};
    vector<int> v(a,a+10);
    shell_sort(v);
    for(int i=0;i<v.size();i++)
        cout<<v[i]<<" ";
    cout<<endl;
    getchar();
    return 0;
}





posted @ 2016-09-01 18:31  gremount  阅读(193)  评论(0编辑  收藏  举报