コンテンツにスキップ

コムソート

出典: フリー百科事典『ウィキペディア(Wikipedia)』
コムソート
Visualisation of comb sort
クラス ソート
データ構造 配列
最悪計算時間 [1]
最良計算時間
平均計算時間 , p は増加数[1]
最悪空間計算量

: comb sort1980 Włodzimierz Dobosiewicz [2][1]1991 Stephen Lacey  Richard Box [3]

O(n log n)

アルゴリズム

[編集]



(一)n 1.3 h

(二)i=0 

(三)i i+h i+h 

(四)i=i+1 i+h>n3

(五)h1

(六)h 1.3 h

Javaによる実装例

[編集]
public static void combSort(int[] data) {
    int h = data.length * 10 / 13;
    
    while (true) {
        int swaps = 0;
        for (int i = 0; i + h < data.length; ++i) {
            if (data[i] > data[i + h]) {
                swap(data, i, i + h);
                ++swaps;
            }
        }
        if (h == 1) {
            if (swaps == 0) {
                break;
            }
        } else {
            h = h * 10 / 13;
        }
    }
}

private static void swap(int[] a, int i, int j) {
    int t = a[i];
    a[i] = a[j];
    a[j] = t;
}

C言語による実装例

[編集]
void comb_sort(int* array, int size) {
    int h = size;
    bool is_swapped = false;

    while (h > 1 || is_swapped) {
        if (h > 1) {
            h = (h * 10) / 13;
        }

        is_swapped = false;
        for (int i = 0; i < size - h; ++i) {
            if (array[i] > array[i + h]) {
                // swap
                int temp = array[i];
                array[i] = array[i + h];
                array[i + h] = temp;
                is_swapped = true;
            }
        }
    }
}

動作例

[編集]



8 4 3 7 6 5 2 1

 n=8  h=8÷1.36 82412

8 4 3 7 6 5 21

243 7 6 5 8 1

2 1 3 7 6 5 8 4

 h = 6÷1.3  4261574

2 1 3 76 5 8 4

2 1 3 4 6 5 8 7

h 3  2  1 

h=3

2 1 3 4 6 5 8 7

h=2

2 1 3 4 6 5 8 7

h=13

2 13 4 6 5 8 7

1 2 3 4 658 7

1 2 3 4 5 6 87

1 2 3 4 5 6 7 8

6

改良版アルゴリズム

[編集]

h=9,10h=11Comb sort 11

h964321107532111864321

参照

[編集]
  1. ^ a b c Brejová, B. (September 2001). “Analyzing variants of Shellsort”. Information Processing Letters 79 (5): 223–227. doi:10.1016/S0020-0190(00)00223-4. 
  2. ^ Włodzimierz Dobosiewicz (1980). “An efficient variation of bubble sort”. Information Processing Letters 11: 5-6. doi:10.1016/0020-0190(80)90022-8. 
  3. ^ "A Fast Easy Sort", Byte Magazine, April 1991