gpt4 book ai didi

c - 选择排序字符 C

转载 作者:行者123 更新时间:2023-11-30 16:46:30 25 4
gpt4 key购买 nike

这是我编写的一个程序,应该使用选择排序方法按字母顺序对单词的各个字符进行排序。

#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

我知道问题源于逻辑,但已经一周了,我仍然无法正确实现选择排序算法或弄清楚我到底需要什么。所以非常欢迎任何意见或建议

最佳答案

像这样

#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);
}

关于c - 选择排序字符 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com