提问人:big_brain-924 提问时间:10/20/2022 最后编辑:John Bollingerbig_brain-924 更新时间:10/20/2022 访问量:35
按字母顺序冒泡 对来自不同结构的字符串进行排序
Alphabetically Bubble Sort strings from different structs
问:
所以我正在做这个项目,在这个项目中,我需要使用冒泡排序对分配的内存中的字符串按字母顺序排序。我对如何做到这一点感到困惑。我尝试了一些我认为会起作用的东西,但它没有,我目前不知所措。
这是我的气泡排序函数:
void sort_customers (int num_customers, float *data_set)
{
float counter, current, swap_temp = data_set;
struct customer customer_1, customer_2, customer_3;
for (customer = 0; customer < num_customers-1; customer++)
for(inner = customer+1; inner < num_customers; inner++)
{
if (strcmp(customer.last_name, inner.last_name) < 0)
{
strcpy (swap_temp, customer.last_name);
strcpy (customer.last_name, inner.last_name);
strcpy (inner.last_name, customer.last_name);
}
}
return;
}
答:
0赞
tsoa
10/20/2022
#1
以下是代码中的一些错误:
- 不能将 a 分配给
float *
float
(swap_temp = data_set
) customer
在外循环中未定义for
inner
在内部循环中未定义for
- 假设 struct 的字段是一个 char 数组,你不能将其转换为
last_name
customer
strcpy
float
(swap_temp
) - 不是错误,但只是比较了两个 char 数组的 ASCII 值,我认为这不是您想要的(大写)
strcmp
- 不是错误,但永远不会使用
counter
current
- 在外部for循环中,似乎和是算术类型,但是您尝试在if语句中从它们中获取“last_name”字段
customer
inner
我写了一个气泡排序程序,对“客户”的名字进行排序,也许这对你有所帮助。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct customer {
/*
* Some other data...
*/
char last_name[20];
};
/* Returns 1 if a > b (alphabetically), 0 otherwise, -1 if same */
int alpha_compare(char *a, char *b, size_t a_size, size_t b_size)
{
for (size_t i = 0; i < a_size && i < b_size; i++) {
if (tolower(a[i]) > tolower(b[i])) {
return 1;
} else if (tolower(a[i]) < tolower(b[i])) {
return 0;
}
}
return -1;
}
void bubble_sort(struct customer *customer_list, size_t num_customers)
{
struct customer swap_buf;
short swap = 1;
while (swap) {
swap = 0;
for (size_t i = 1; i < num_customers; i++) {
switch (alpha_compare(customer_list[i-1].last_name, customer_list[i].last_name, 20, 20)) {
case 1:
{
swap_buf = customer_list[i-1];
customer_list[i-1] = customer_list[i];
customer_list[i] = swap_buf;
swap = 1;
}
default: break;
}
}
}
}
int main()
{
// These are example "last names"
struct customer c1 = {"tower"};
struct customer c2 = {"tree"};
struct customer c3 = {"banana"};
struct customer c4 = {"bird"};
struct customer c5 = {"apple"};
struct customer customer_list[] = {c1, c2, c3, c4, c5};
bubble_sort(customer_list, 5);
for (int i = 0; i < 5; i++) {
printf("%s\n", customer_list[i].last_name);
}
}
如果需要,维基百科提供了对气泡排序算法的一个很好的概述。
下一个:结构的动态内存分配和函数传递
评论
customer
inner
data_set
float
swap_temp
float
last_name