Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

c - Bubble Sort using pointers to function

I'm trying to implement a bubble sort in c by using pointers to function but does not work. Can anyone help me? Here is the code:

#include <stdio.h>
#include <stdlib.h>

void bubbleSort(void** base, size_t length, int (*compar)(const void*, const void*));

int main(int argc, char* argv[]) {
    int cmp(const void*, const void*);
    int vet[] = {1, 2, 5, 7, 6, 1, 3, 2, 9, 15, 14, 20};
    bubbleSort((void**) &vet, sizeof(vet)/sizeof(vet[0]), cmp);
    int i;
    for (i = 0; i < sizeof(vet)/sizeof(vet[0]); i++) {
        printf("%d
", vet[i]);
    }
    return 0;
}

int cmp(const void* x, const void* y) {
    return **((int* const*) x) - **((int* const*) y);
}

void bubbleSort(void** base, size_t length, int (*compar)(const void*, const void*)) {
     int i, j;
     void swap(void*, void*);
     for (i = 0; i < length; i++) {
       for (j = 1; j < length; j++) {
           if ((*compar)(base[i], base[i]) < 0) {
               swap(base[i], base [j]);
           }
       }
     }
}

void swap(void* a, void* b) {
     void* tmp = a;
     a = b;
     b = tmp;
}

The output is the same vector without sorting. (Sorry for my English)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp(const void *x, const void *y){
    int a = *(const int *)x;
    int b = *(const int *)y;
    return a < b ? -1 : (a > b);
}

void swap(void *a, void *b, size_t type_size) {
    void *tmp = malloc(type_size);
    memcpy(tmp, a, type_size);
    memcpy(a,   b, type_size);
    memcpy(b, tmp, type_size);
    free(tmp);
}

void bubbleSort(void *base, size_t length, size_t type_size, int (*compar)(const void*, const void*)) {
    int i, j;
    for (i = 0; i < length - 1; ++i) {
        for (j = i+1; j < length; ++j){
            char *data_i = (char*)base + type_size * i;
            char *data_j = (char*)base + type_size * j;
            if(compar(data_i, data_j) > 0)
                swap(data_i, data_j, type_size);
        }
    }
}

int main() {
    int vet[] = {1, 2, 5, 7, 6, 1, 3, 2, 9, 15, 14, 20};
    bubbleSort(vet, sizeof(vet)/sizeof(*vet), sizeof(*vet), cmp);
    int i;
    for (i = 0; i < sizeof(vet)/sizeof(*vet); i++) {
        printf("%d
", vet[i]);
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...