标签:pac src 希尔 blog turn nbsp height namespace i++
希尔排序
按一定间隔交换元素
原始希尔排序:
Dm = [N/2], Dk = [Dk+1/2]
void Shell_sort(ElementType A[], int N) { int D, P, i; ElementType Tmp; for (D = N/2; D > 0; D/= 2) { for (P = D; P < N; P++) { Tmp = A[P]; for (i = P; i >= D && A[i-D]>Tmp; i-=D) A[i] = A[i-D]; A[i] = Tmp; } } }
最坏情况:T = θ(N^2)
增量序列
代码:
#include <iostream> typedef long long ElementType; using namespace std; void ShellSort(ElementType A[], int N) { //采用Sedgewick增量序列 int Si, D, P, i; ElementType Tmp; //部分增量 int Sedgewick[] = {929, 505, 209, 41, 19, 5, 1, 0}; for (Si = 0; Sedgewick[Si] >= N; Si++) ; //初始增量Sedgewick[Si]不能超过待排序列长度 for (D = Sedgewick[Si]; D > 0; D = Sedgewick[++Si]) for (P = D; P < N; P++) { Tmp = A[P]; for (i = P; i >= D && A[i-D] > Tmp; i-= D) A[i] = A[i-D]; A[i] = Tmp; } } int main() { int N; ElementType A[110000]; cin >> N; for (int i = 0; i < N; i++) cin >> A[i]; ShellSort(A, N); for (int i = 0; i < N-1; i++) cout << A[i] << " "; cout << A[N-1]; return 0; }
PTA运行结果:
标签:pac src 希尔 blog turn nbsp height namespace i++
原文地址:http://www.cnblogs.com/whileskies/p/6864352.html