【发布时间】:2015-04-30 05:31:10
【问题描述】:
这是一个用于对名称列表进行排序的 c 程序示例...我是算法新手,所以我需要知道它是什么类型! 我也可以将它用于哪些现实生活中的例子?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
char *str[5], *temp;
int i, j, n;
printf("\nHow many names do you want to have?");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter the name %d: ", i);
flushall();
gets(str[i]);
}
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
flushall();
printf("\nSorted List : ");
for (i = 0; i < n; i++)
puts(str[i]);
return (0);
}
【问题讨论】:
-
你写的时候是怎么想的?
-
实际上,您是否尝试过运行它?它应该以可怕的方式爆炸,因为没有为字符串分配内存。
-
在我看来像 冒泡排序。
-
该代码具有未定义的行为,
temp在用作strcpy()调用中的目标之前从未被初始化为有效指针。可怕的。str[]的内存“管理”同样缺失,它使用gets()。哎呀。 -
@AhmedSamir 好吧,那么可以认为该特定资源的质量低于合理水平。停止使用它,因为它只会教你 cr*p,你以后将不得不忘记。
标签: c algorithm sorting computer-science