【发布时间】:2013-02-16 14:05:53
【问题描述】:
我有一个字符数组
char word[30];
保留用户将输入的单词,我想对字母进行排序 例如,如果这个词是 "cat" 我想让它成为一个“行为” 我想这是相当容易的任务,但作为 C 编程的初学者,我发现互联网上的示例相当混乱。
这是我尝试进行冒泡排序的代码...
还是不行
#include <stdio.h>
#include<string.h>
#define MAX_STRING_LEN 30
main()
{
char w1[30], w2[30];
char tempw1[30], tempw2[30];
int n,i,k;
char temp;
printf("Give the first word: ");
scanf("%s",&w1);
printf("Give the second word: ");
scanf("%s",&w2);
if(strlen(w1)==strlen(w2)) /* checks if words has the same length */
{
strcpy(tempw1,w1); /*antigrafei to wi string sto tempw1 */
strcpy(tempw2,w2); /*antigrafei to w2 string sto tempw2 */
n=strlen(w1);
for (i=1; i<n-1; i++)
{
for (k=n;k>i+1;k--)
{
if (w1[k] < w1[k-1])
{
temp=w1[k-1];
w1[k-1]=w1[k];
w1[k]=temp;
}
}
}
for (i=1; i<n-1; i++)
{
for (k=n;k>i+1;k--)
{
if (w2[k] < w2[k-1])
{
temp=w2[k-1];
w2[k-1]=w2[k];
w2[k]=temp;
}
}
}
printf("%s \n",tempw1);
printf("%s \n",w1);
printf("%s \n",tempw2);
printf("%s \n",w2);
/* call qsort */
/* call compare */
}
else printf(" \n H lexh %s den einai anagrammatismos tis lexhs %s",w1,w2);
return 0;St
【问题讨论】:
-
冒泡排序是一种更简单的排序算法。
-
好的,谢谢您提出的冒泡排序建议,我认为这只适用于整数!我马上试试,我正在尝试使用的程序是一个字谜游戏,作为练习,我已经解决了我比较两个数组但需要先对它们进行排序才能比较的所有其他部分。
-
@poseidon11 1. 字符是整数。 2. 你可以想出某种算法,根据对象的属性来比较对象,否则就不会有通用的排序算法。