如何在C中实现计数排序来对字符数组进行排序



因此,我正在尝试实现计数排序算法来对用户给定的数字数组进行排序,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,n=15;
char arr[]={"ABEFGEAGCEDBFAC"}; //I'm using this string to test it out
/*for(int i=0; i<n; i++){
printf("Insert a letter %d: ",i+1);
scanf("%c",&arr[i]);
fflush(stdin);
}
*/
printf("Array: n[ ");
for(i=0; i<n; i++){
if(i<n-1)
printf("%c | ",arr[i]);
if(i==n-1)
printf("%c ]n",arr[i]);
}
printf("n");
int range[7];
for(i=0;i<7;i++){
range[i]=0;
}
for(i=0; i<n; i++){ //I've seen other ways to do this, but I just need it to go from A-G
//not sure if this is the problem.
switch(arr[i]){
case 'A':
range[0]++;
break;
case 'B':
range[1]++;
break;
case 'C':
range[2]++;
break;
case 'D':
range[3]++;
break;
case 'E':
range[4]++;
break;
case 'F':
range[5]++;
break;
case 'G':
range[6]++;
break;
}
}
printf("Counting array (number of times it appear in the array): n[ ");
for(i=0; i<7; i++){
if(i<6)
printf("%d | ",range[i]);
if(i==6)
printf("%d ]n",range[i]);
}
printf("n");
for(i=1;i<7;i++){ //Here I do the sum of all elements in the array
range[i] = range[i] + range[i-1];
}
printf("Sum of the array: n[ ");
for(int i=0; i<7; i++){
if(i<6)
printf("%d | ",range[i]);
if(i==6)
printf("%d ]n",range[i]);
}
printf("n");
char ord[15];
for(i=n-1;i>=0;i--)
ord[--range[arr[i] - 'A']] = arr[i];
for (i=0;i<n;i++){
printf("%c ",ord[i]);
}
/*
printf("Ord: n[ ");
for(int i=0; i<15; i++){
if(i<14)
printf("%c | ",ord[i]);
if(i==14)
printf("%c ]n",ord[i]);
}
*/
}

所以,正如你所看到的,如果我没有错的话,错误是当我试图使用句子的倒数第二个中的范围数组将每个字母放在正确的位置时。我已经看到了其他实现它的方法,但我就是做不到,当我试图打印ord[I]时,它就崩溃了。我很难完全理解中发生了什么。

更新:
尝试对代码执行fish-404的更正,如上所示。无法正确实施

上次更新:
上面的代码现在已经完成并完全可用。感谢@fish-404。

在这一行中,arr[i]是一个char,您尝试使用char作为数组range的索引。

ord[range[arr[i]]] = arr[i];

更新

如果我理解正确的话,我认为您希望使用arr[i]字符作为在range数组中搜索的索引。

正如你所看到的,你使用的range数组计算字母,要使用字母进行索引,你只需要使用arr[i]-'A'来计算range数组中的字母顺序。

for (i = n; i >= i; i--)
ord[--range[arr[i] - 'A']] = arr[i];
// use this to see result
for (i = n;i >= 1; i--)
printf("i: %d, ord[i]: %cn", i, ord[i-1]);

最新更新