对二维字符数组中的列进行排序
我有一个二维数组,其中顶行是一行字母(字母表),底行是上面的字母在字符串中出现的频率。这个想法是将字母按照出现频率的顺序排列在顶行。
目前:
输入:
quickbrownfoxjumpsoverthelazydog
输出:
abcdefghijklmnopqrstuvwxyz
11112111111111411211211111
所需输出:
oeruabcdfghijklmnpqstvwxyz
42221111111111111111111111
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
main()
{
char string[100];
char s[26][2];
int c = 0, count[26] = {0};
printf("Enter a string\n");
gets(string);
while ( string[c] != '\0' )
{
if ( string[c] >= 'a' && string[c] <= 'z' )
count[string[c]-'a']++;
c++;
}
for ( c = 0 ; c < 26 ; c++ )
{
if( count[c] != 0 )
{
s[c][1]=c+'a';
s[c][2]= (char)(((int)'0')+count[c]);
gotoxy(c,1);
printf("%c",s[c][1]);
gotoxy(c,2);
printf("%c",s[c][2]);
}
}
return 0;
}
I have a 2D array where the top row is a row of letters (the alphabet) and the bottom row is the frequency that the letter above it occurs in a string. The idea is to place the letters in order of frequency along the top row.
At the moment:
input:
quickbrownfoxjumpsoverthelazydog
output:
abcdefghijklmnopqrstuvwxyz
11112111111111411211211111
Desired output:
oeruabcdfghijklmnpqstvwxyz
42221111111111111111111111
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
main()
{
char string[100];
char s[26][2];
int c = 0, count[26] = {0};
printf("Enter a string\n");
gets(string);
while ( string[c] != '\0' )
{
if ( string[c] >= 'a' && string[c] <= 'z' )
count[string[c]-'a']++;
c++;
}
for ( c = 0 ; c < 26 ; c++ )
{
if( count[c] != 0 )
{
s[c][1]=c+'a';
s[c][2]= (char)(((int)'0')+count[c]);
gotoxy(c,1);
printf("%c",s[c][1]);
gotoxy(c,2);
printf("%c",s[c][2]);
}
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种方法:每次计数后,将其左移五位,然后按位或低五位中的字母数。对结果数字进行排序,并通过与
0x1F
进行“与”运算并添加'a'
将其最低有效五位转换回字母。Here is one approach: take each count, shift it left by five, and bitwise-or the number of the letter in the lower five bits. Sort the resulting numbers, and convert their least-significant five bits back to the letter by and-ing with
0x1F
and adding'a'
.有几点:
s[c][0]
和s[c][1]
- 你的代码没有崩溃,因为你很幸运。c[2][26]
至于排序……因为我们只处理 26 个元素,而不是 260 万个元素,那么如何以及何时排序这没什么影响。你可以通过冒泡排序来逃脱。您可以花哨地构建某种双向链接列表,然后对其进行排序,并重新排列元素。玩得开心!
A couple of things:
s[c][0]
ands[c][1]
- your code isn't crashing b/c you're lucky.c[2][26]
As to the sorting … since we're only working with 26 elements and not 2.6 million, how and when you do it is of little consequence. You can get away with doing a bubble sort. You could get fancy and build some sort of doubly-linked list and sort it as you go, shuffling elements around. Have fun with it!
您应该找到每次迭代的最大值。你可以使用一些快速排序算法,但一个简单的解决方案是:(
当然,假设max<10)
You should find the maximum every iteraton. You can use some fast sort algorithm, but a simple solution is:
(Of course, assuming that max<10)