gpt4 book ai didi

c - C 中的通用快速排序

转载 作者:行者123 更新时间:2023-12-05 03:25:33 26 4
gpt4 key购买 nike

<分区>

谁能告诉我在这个伪代码 Quicksort 之后的通用快速排序代码中我做错了什么& Partition ,该算法有效,因为我已经通过将 int 数组传递给 quicksortpartition 函数,仅使用整数完成了它,而没有比较函数,但我试图让它同时适用于 int 和字符串。在这段代码中,我只测试了 int 值,但代码不起作用,输出是数组的初始值,它与字符串完全相同,我得到相同的初始数组作为输出。我已经评论了字符串部分,因为它们的排序方式与整数相同。这是有效的整数代码 Integer working code :

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

//prototipi delle funzioni
typedef int (*compare_function)(const void *, const void *);

void generic_quicksort(void *v, int i, int f, size_t size, compare_function compare);
void generic_swap(void *a, void *b, size_t size);
int generic_partition(void *v, int i, int f, size_t size, compare_function compare);

void print_int_array(const int *array, size_t len) {
size_t i;

for (i = 0; i < len; i++)
printf("%d | ", array[i]);

putchar('\n');
}

//funzione di confronto
int compare_int(const void *, const void *);

int compare_str(const void *a, const void *b) {
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
/* strcmp functions works exactly as expected from
comparison function */
}

void print_cstring_array(char **array, size_t len) {
size_t i;

for (i = 0; i < len; i++)
printf("%s | ", array[i]);

putchar('\n');
}

int main() {
int v[] = { 5, 4, 3, 2, 1 };
char *strings[] = { "Zorro", "Alex", "Celine", "Bill", "Forest", "Dexter" };

int n = sizeof(v) / sizeof(int);

print_int_array(v, n);

generic_quicksort((void *)v, 0, n - 1, sizeof(int), compare_int);

print_int_array(v, n);

/*

int s = sizeof(strings) / sizeof(*char);

print_cstring_array(strings, s);

generic_quicksort((void *)strings, 0, s - 1, sizeof(*char), compare_str);

print_cstring_array(strings, s);
*/
return 0;
}

int compare_int(const void *a, const void *b) {
return *((int*)a) - *((int*)b);
}

void generic_quicksort(void *v, int i, int f, size_t size, int (*comp)(const void *, const void *)) {
if (i >= f)
return;

int p = generic_partition(v, i, f, size, comp);

generic_quicksort(v, i, p - 1, size, comp);
generic_quicksort(v, p + 1, f, size, comp);
}

void generic_swap(void *a, void *b, size_t size) {
void *tmp = malloc(size);

memcpy(tmp, a, size);
memcpy(a, b, size);
memcpy(b, tmp, size);

free(tmp);
}

int generic_partition(void *v, int i, int f, size_t size, int (*comp)(const void *, const void *)) {

void *x = malloc(size);
int k, j;

memcpy(x, v + (i * size), size);

k = i - 1;

for (j = i; j <= f - 1; j++) {
if (comp(v + (j * size), x) <= 0) {
k++;
generic_swap(v + (k * size), v + (j * size), size);
}
}

generic_swap(v + ((k + 1) * size), v + (f * size), size);

free(x);

return (k + 1);
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com