ALDS1_2_D-Shell Sort

Shell Sort(希爾排序)
Shell Sort is a generalization of Insertion Sort to arrange a list of n elements A.

1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,…, ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every g-th elements. Beginning with large values of g, it repeats the insertion sort with smaller g.

Your task is to complete the above program by filling ?. Write a program which reads an integer n and a sequence A, and prints m, Gi(i=0,1,…,m−1) in the pseudo code and the sequence A in ascending order. The output of your program must meet the following requirements:

1≤m≤100
0≤Gi≤n
cnt does not exceed ⌈n1.5⌉
Input
In the first line, an integer n is given. In the following n lines, Ai(i=0,1,…,n−1) are given for each line.

Output
In the first line, print an integer m. In the second line, print m integers Gi(i=0,1,…,m−1) separated by single space character in a line.
In the third line, print cnt in a line. In the following n lines, print Ai(i=0,1,…,n−1) respectively.

This problem has multiple solutions and the judge will be performed by a special validator.

Constraints
1≤n≤1,000,000
0≤Ai≤109
Sample Input 1
5
5
1
4
3
2
Sample Output 1
2
4 1
3
1
2
3
4
5
Sample Input 2
3
3
2
1
Sample Output 2
1
1
3
1
2
3


#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;

//g數組
vector<int>G;
long long cnt;
int A[1000000 + 10];

// 間隔爲g的插入排序
void insertionSort(int A[], int n, int g) {
    for (int i = g; i < n; i++) {
        int v = A[i];
        int j = i - g;
        while (j >= 0 && A[j] > v) {
            A[j + g] = A[j];
            j -= g;
            cnt++;
        }
        A[j + g] = v;
    }
}
//希爾排序
void shellsort(int A[], int n) {
    for (int i = G.size() - 1; i >= 0; i--) {
        insertionSort(A, n, G[i]);
    }
}

// 生成g數組
void getArray(int n) {
    for (int h = 1; h <= n;) {
        G.push_back(h);
        h = 3 * h + 1;
    }
}


int main() {

    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        scanf("%d", &A[i]);
    getArray(n);
    shellsort(A,n);

    int len = G.size();
    printf("%d\n", len);
    for (int i = len - 1; i >= 0; i--)
        printf("%d%c", G[i], i == 0 ? '\n' : ' ');
    printf("%lld\n", cnt);
    for (int i = 0; i < n; i++)
        printf("%d\n", A[i]);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章