bubble在c中按字母顺序对字符数组进行排序

我正在尝试按字母顺序对字符数组进行冒泡。 我的代码如下:

#define CLASS_SIZE 10 #include  void bubbleSortAWriteToB(const char a[], char *b[]); int main(void){ char *s_letters[CLASS_SIZE]; char letters[CLASS_SIZE] = {'a','r','p','b','r','c','x','e','w','j'}; bubbleSortAWriteToB(letters,s_letters); return 0; } void bubbleSortAWriteToB(const char a[], char *b[]){ char temp; int i,j; for(i=0;i<CLASS_SIZE-1;i++){ for(j=1;j(int)a[j]){ temp = a[j]; *b[j] = a[j-1]; *b[j-1] = temp; } } } } 

它没有给出任何类型的错误,但是当我运行它时它会像在inifinte循环中那样陷入困境。 但从我所看到的情况来看也不是这样。 你能帮我吗?

修复你的代码

首先,您的代码存在一些非常严重的基本问题。 在我们解决这些问题之前,让我们先解决你到目前为止的问题。 您的排序循环似乎是对数组进行一半排序,一半对b数组进行排序。 你也从来没有初始化b数组来包含任何值。 以下是您的代码的更正版本:

 #define CLASS_SIZE 10 #include  void bubbleSortAWriteToB(const char a[], char * b[]); int main(void){ int i; // initialize array char * s_letters[CLASS_SIZE]; char letters[CLASS_SIZE] = {'a','r','p','b','r','c','x','e','w','j'}; // sort array bubbleSortAWriteToB(letters,s_letters); // print sorted array for (i=0;i*b[j]){ temp = b[j]; b[j] = b[j-1]; b[j-1] = temp; } } } } 

修复方法是使用指向a的点初始化b数组,然后通过比较数组中的相应值来就地对b数组进行排序。


简化代码

在您的原始代码中,策略是有一个指针数组(b)指向a中的元素,然后进行排序。 这在这里是不必要的,因为字符小于指针,所以让b是一个字符数组更节省空间和更简单。

而且,你的间距非常紧凑,有些难以阅读。 这是一个使用b作为字符数组而不是指针的解决方案,并提供改进的间距。 此外,没有必要声明上述function。 定义函数并声明一次就足够了。

 #define CLASS_SIZE 10 #include  void bubbleSortAWriteToB(const char a[], char b[]){ char temp; int i,j; // initialize b array to hold pointers to each element in a for (i = 0; i < CLASS_SIZE; i++){ b[i] = a[i]; } // in-place sort the b array for(i = 0; i < CLASS_SIZE; i++){ for(j = i + 1; j < CLASS_SIZE - 1; j++){ if(b[j-1] > b[j]){ temp = b[j]; b[j] = b[j-1]; b[j-1] = temp; } } } } int main(void){ int i; // initialize array char s_letters[CLASS_SIZE]; char letters[CLASS_SIZE] = {'a','r','p','b','r','c','x','e','w','j'}; // sort array bubbleSortAWriteToB(letters, s_letters); // print sorted array int i; for (i = 0; i < CLASS_SIZE; i++){ printf("%c\n", s_letters[i]); } return 0; } 

您的s_letters未正确初始化,但您可以在以下位置访问它:

 *b[j] = a[j-1]; *b[j-1] = temp; 

这是一个段错误。

我用gcc -g编译了这个并通过Valgrind运行它,得到了这个:

 ==54446== Non-existent physical address at address 0x100000000 ==54446== at 0x100000EB0: bubbleSortAWriteToB (xc:20) ==54446== by 0x100000DFE: main (xc:9) 

第20行是这样的:

 *b[j] = a[j-1]; 

char *b[]是一个char指针数组,但你试图在指针中添加一些内容而不初始化它们。 如果你真的想这样做,你需要:

 b[j] = malloc(sizeof(*b[j])); // Create some space for a char *b[j] = a[j-1]; // Put the char in that space 

但是,我认为这不是你真正想要的。 如果您只是将其更改为char b[] ,并删除所有* ,则可以正常工作。

冒泡排序

控制台:输入:“face321”OutPut:“123acef”

  #include  int main(){ char c[80] = "0"; char temp = '0'; int offSet = 0; int i = 0; int j =0; int count =0; printf("Enter first string: "); gets(c); while (*(c + offSet) != '\0') { count++; offSet++; } for (i = 0; i < count; i++) { for (j = 0; j < count - 1; j++) { if (c[j]>c[j + 1]) { temp = c[j]; c[j] = c[j + 1]; c[j + 1] = temp; } } } puts(c); return 0; }