希尔排序-----快排的进化

分析:分组插排    
//时间复杂度:
最好:O(n)
平均:O(n^1.3~1.4)
最差:O(n^2)

空间复杂度:O(1)
稳定性:不稳定
*/

#pragma once
#include<stdio.h>

void InsertSortWithGap(int array[], int size, int gap){
    for (int i = 0; i < size; i++){
        int key = array[i];
        int j;
        //[i-1,0]
        for (j = i - gap; j >= 0; j -= gap){
            if (array[j] <= key){
                break;
            }
            array[j + gap] = array[j];
        }

        array[j + gap] = key;
    }
}


void ShellSort(int array[], int size){
    int gap = size;
    while (1){
        gap = gap / 3 + 1;
        //gap = gap / 2;
        InsertSortWithGap(array, size, gap);
        if (gap == 1){
            return;
        }
    }
}


void PrintArray(int array[], int size){
    for (int i = 0; i < size; i++){
        printf("%d  ", array[i]);
    }
    printf("\n");
}
void test(){
    int array[] = { 3, 9, 1, 4, 7, 5, 2, 8, 0 ,10, 9 };
    int size = sizeof(array) / sizeof(int);
    PrintArray(array, size);
    ShellSort(array, size);
    PrintArray(array, size);
}

结果:

3  9  1  4  7  5  2  8  0  10  9
0  1  2  3  4  5  7  8  9  9  10
请按任意键继续. . .
 

猜你喜欢

转载自blog.csdn.net/qq_41832361/article/details/90061893
今日推荐