微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

排序后如何将字符串与适当的整数连接起来?

如何解决排序后如何将字符串与适当的整数连接起来?

有人可以帮我用 C 语言解决这个问题吗?我需要按字母顺序和分数对排行榜进行排序,这很有效。我使用 atoi()字符串转换为整数,但名称保持它们离开的顺序。这是排序函数

void bubbleSort2(int arr[],int n)
{
    int c,d;
    int swap;
    for (c = 0; c < n - 1; c++)
    {
        for (d = 0; d < n - c - 1; d++)
        {
            if (arr[d] < arr[d + 1])
            {
                swap = arr[d];
                arr[d] = arr[d + 1];
                arr[d + 1] = swap;
            }
        }
    }
}

void sortscores() {
    FILE* fp = openFile();
    int x[128];
    char line[128][20];
    int i = 0,j = 0;
    int tot = 0;
    while (fgets(line[i],20,fp))
    {
        line[i][strlen(line[i]) - 1] = '\0';
        i++;
    }
    tot = i;
    for (int i = 0; i < tot; i++)
    {   
        char* sep = strchr(line[i],' ');
        *sep = '\0';
        x[i] = atoi(sep + 1);
    }
    bubbleSort2(x,tot);
    printf("Sorted by scores:\n");
    for (int i = 0; i < tot; i++)
    {
        printf("%s %d\n",line[i],x[i]);
    }
    fclose(fp);
}

输出如下:

Sorted alphabetical:
Branimir 100
Branimir 700
Brekalo 100
Hrvoje 350
Ilija 0
Ilija 50
Marin 100
Marin 400
Marko 0
Marko 300
Matej 0
Matej 900
nikola 0
Pero 100
Pero 150
Ramal 100
Simun 550
Skoric 0

Sorted by scores:
Ramal 900
Ilija 700
Ilija 550
Pero 400
Pero 350
nikola 300
Marko 150
Marin 100
Marko 100
Marin 100
Matej 100
Branimir 100
Matej 50
Branimir 0
Brekalo 0
Skoric 0
Hrvoje 0
Simun 0

Matej 应该首先按分数排序,而不是 Ramal。我希望你能帮我解决这个问题。

解决方法

您只是对值进行排序,而不是对名称进行排序。

同时更改排序函数中char line[128][20]的索引。

在主函数中 pass DateTextField( {required this.dateComposition,required this.dateCompositionHintText,required this.onFieldSubmitted,required this.onChanged,required this.focusNode}); ;

在冒泡排序中

class DateTextField extends StatelessWidget {
  DateTextField(
      {required this.dateComposition,this.onFieldSubmitted,this.onChanged,this.focusNode});

  //dateComposition can only have Day,Month,or Year as strings
  final String dateComposition;
  final String dateCompositionHintText;
  final Function ?onFieldSubmitted;
  //onchanged function has to be determined if you want to automatically set the focus to another text field,see application on age_screen with the datetextfields
  final Function ?onChanged;
  //set the widget with its focusnode
  final FocusNode focusNode;
}

希望有帮助:)

,

您需要使用结构来存储数据。

#define MAXNAME 20

typedef struct
{
    int score;
    char name[MAXNAME];
}student;

void bubbleSort2(student arr[],size_t n)
{
    /* ..... */
    if (arr[d].score < arr[d + 1].score)

    /* etc etc */
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。