希尔排序 ShellSort

void *shellSort(void *base, size_t nmeb, size_t size, int(*compar)(const void *, const void *))
{
    int i, j, gap;

    gap = 0;
    while (gap <= nmeb) {
        gap = gap * 3 + 1;
    }

    while (gap > 0) {
        for (i = gap; i < nmeb; i++) {
            for (j = i; j >= gap; j -= gap) {
               if (compar(base + (j- gap) * size, base + j * size) > 0) {
                    swap(base + (j - gap)* size, base + j * size, size);
                } else
                    break; 
            }
        }
        gap = (gap - 1) / 3;
    }
}

void swap(void *p1, void *p2, size_t size)
{
    void *temp;

    temp = malloc(size);
    if (temp == NULL) {
        exit(EXIT_FAILURE);
    }

    memcpy(temp, p1, size);
    memcpy(p1, p2, size);
    memcpy(p2, temp, size);

    free(temp);
}

int comparStr(const void *p1, const void *p2)
{
    return strcmp(* (char * const *) p1, * (char * const *) p2);
}

int comparInt(const void *p1, const void *p2)
{
    return (*(const int *) p1 - *(const int *) p2);
}


    简单测试:


int main(int argc, char *argv[])
{
    int i;
    int arr[5] = {4, 2, 1, 3, 5};

    printf("Integer Sort\n");
    printf("Original: ");
    for (i = 0; i < 5; i++)
        printf("%d ", arr[i]);
    printf("\n");

    shellSort(arr, 5, sizeof(int), comparInt);

    printf("Sorted  : ");
    for (i = 0; i < 5; i++)
        printf("%d ", arr[i]);
    printf("\n\n");

    if (argc < 2)
        exit(EXIT_SUCCESS);

    printf("String Sort\n");
    printf("Original: ");
    for (i = 1; i < argc; i++)
        printf("%s ", argv[i]);
    printf("\n");

    shellSort(&argv[1], argc - 1, sizeof(argv[1]), comparStr);
    printf("Sorted  : ");
    for (i = 1; i < argc; i++)
        printf("%s ", argv[i]);
    printf("\n");

    exit(EXIT_SUCCESS);
}

    结果如下:


roo@ubuntu:~/roose/algorithm$ ./a.out mac windows linux
Integer Sort
Original: 4 2 1 3 5 
Sorted  : 1 2 3 4 5 

String Sort
Original: mac windows linux 
Sorted  : linux mac windows




你可能感兴趣的:(shell,希尔排序,sort)