这是我编写的一个程序,它应该使用选择排序方法按字母顺序对单个字符的字符进行排序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char str[100];
void alphaOrder(){
for(int i=0;str[i]!='\0';++i){ //iterate until end of entered string
if(str[i+1]==' ' || str[i+1]==NULL){ // iterate until end of current word
int wordLength=0; // finds amount of letters in current word
for(int j=i;j>=0 && str[j]!=' ';j--){
wordLength+=1;
}
int smallest=1000;
int prv = 1000;
for(int k=0;k != wordLength;++k){
int counter=0; //loops through letters in word printing and storing the smallest
while(counter!=wordLength){
if(k==0){ // this if loop only occurs during for 1st char of word
if(str[i-counter] < smallest){
smallest=str[i-counter];
}
}
else{
if(str[i-counter] > smallest && str[i-counter] < prv){
smallest=str[i-counter];
prv=smallest;
}
}
++counter;
}
printf("%c",smallest);
}
}
}
但是我的问题源于这个片段中的逻辑:
for(int k=0;k != wordLength;++k){
int counter=0; //loops through letters in word printing and storing the smallest
while(counter!=wordLength){
if(k==0){ // this if loop only occurs during for 1st char of word
if(str[i-counter] < smallest){
smallest=str[i-counter];
}
}
else{
if(str[i-counter] > smallest && str[i-counter] < prv){
smallest=str[i-counter];
prv=smallest;
}
}
++counter;
}
printf("%c",smallest);
例如:
input: hello world
output:eoooo ddddd
我知道这个问题源于逻辑,但已经过了一周,我仍然无法正确实现选择排序算法或弄清楚我需要什么。 所以任何建议或建议都受到欢迎
答案 0 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void alphaOrder(char *str){
char *p = str;
while(*p){
while(isspace((unsigned char)*p))
++p;//skip space
if(!*p)//end of string?
break;
char *word = p;//top of word
while(*p && !isspace((unsigned char)*p))
++p;//in word
//selection sort
int word_length = p - word;
for(int i = 0; i < word_length -1; ++i){
int smallest = i;
for(int j = i + 1; j < word_length; ++j){
if(word[smallest] > word[j])
smallest = j;
}
if(i != smallest){
char temp = word[i];
word[i] = word[smallest];
word[smallest] = temp;
}
}
}
}
int main(void){
char str[100+1];
fgets(str, sizeof str, stdin);
alphaOrder(str);
puts(str);
}