使用指针进行气泡排序 [英] Bubble Sort using pointers to function

查看:99
本文介绍了使用指针进行气泡排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用指针来实现c中的冒泡排序,但是不起作用.谁能帮我?这是代码:

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\n", 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)

推荐答案

#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\n", vet[i]);
    }
    return 0;
}

这篇关于使用指针进行气泡排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆