日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C++實(shí)現(xiàn)希爾排序算法實(shí)例_C 語(yǔ)言

作者:恒天1020 ? 更新時(shí)間: 2022-03-25 編程語(yǔ)言

1.代碼模板

// 希爾排序(Shell Sort)
void ShellSort(SqList *L)
{
    int i, j;
    int increment = L->length;  // 先讓增量初始化為序列的長(zhǎng)度
    do {
        increment = increment / 3 + 1;   // 計(jì)算增量的值
        for (i = increment + 1; i <= L->length; i ++ ) { 
            if (L->arr[i] < L->arr[i - increment]) {   // 如果L->[i]需要插入有序增量子表
                L->arr[0] = L->arr[i];   // 暫存在哨兵位
                for (j = i - increment; j > 0 && L->arr[0] < L->arr[j]; j -= increment) {  // 遍歷增量子表,尋找插入位置
                    L->arr[j + increment] = L->arr[j];
                }
                L->arr[j+increment] = L->arr[0];  // 插入
            }
        }
    } while (increment > 1);
}

2.算法介紹

希爾排序,又叫縮小增量排序,算法屬于插入類排序的進(jìn)階算法,采取跳躍分割的策略,將關(guān)鍵字較小的元素跳躍式的往前挪,大大減小了交換比較的次數(shù)。使得序列整體基本有序 ,即大的元素基本在后面,小的元素基本在前面,不大不小的元素基本在中間。

希爾排序的關(guān)鍵在于將序列中相隔某個(gè)“增量”的元素組成一個(gè)子序列,且序列的最后一個(gè)增量必須為1,這樣才能保證最后的結(jié)果是有序且正確的。但增量如何選擇為最佳,至今仍無(wú)定論。且由于元素是跳躍式移動(dòng)的,所有希爾排序是一個(gè)不穩(wěn)定的排序算法,其時(shí)間復(fù)雜度受到增量選擇的影響,最好為O(n^1.3) , 最壞為O(n*n)。

3.實(shí)例

#include <iostream>
using namespace std;

const int N = 100;

typedef struct
{
    int arr[N];    // 存儲(chǔ)待排序的序列
    int length;    // 存儲(chǔ)序列的長(zhǎng)度
} SqList;

void ShellSort(SqList *L)
{
    int i, j;
    int increment = L->length;
    do {
        increment = increment / 3 + 1;
        for (i = increment + 1; i <= L->length; i ++ ) {
            if (L->arr[i] < L->arr[i - increment]) {
                L->arr[0] = L->arr[i];
                for (j = i - increment; j > 0 && L->arr[0] < L->arr[j]; j -= increment)
                    L->arr[j + increment] = L->arr[j];
                L->arr[j + increment] = L->arr[0];
            }
        }
    } while (increment > 1);
}

int main()
{
    SqList L;
    L.arr[1] = 50;
    L.arr[2] = 10;
    L.arr[3] = 90;
    L.arr[4] = 30;
    L.arr[5] = 70;
    L.arr[6] = 40;
    L.arr[7] = 80;
    L.arr[8] = 60;
    L.arr[9] = 20;
    L.length = 9;

    ShellSort(&L);
    for (int i = 1; i <= L.length; i ++ )
        cout << L.arr[i] << " ";

}

原文鏈接:https://blog.csdn.net/weixin_51424157/article/details/122344532

欄目分類
最近更新