gaaa515 2021-12-06 17:21 采纳率: 92.3%
浏览 19
已结题

关于C语言冒泡排序,让下列四个国家按人口从高到低排

问题遇到的现象和发生背景

到这就想不出来了,有没有大神会的。。
main函数需要呼出bubble_sort_countries

问题相关代码,请勿粘贴截图

#include <stdio.h>

#define COUNTRYNO 4

void bubble_sort_countries(int countries[COUNTRYNO],int n){
int i,j,tmp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (countries[j] > countries[j + 1]) {
tmp = countries[j];
countries[j] = countries[j + 1];
countries[j + 1] = tmp;
}
}
}
}

struct Country {
char country_name[50];
int population;
};

int find_most_populated( struct Country * );

int main( void ) {
struct Country countries[COUNTRYNO] = {
{ "United States", 331 },
{ "China", 1439 },
{ "Japan", 126},
{ "Brazil", 212 }
};
bubble_sort_countries(countries[], 5);
for (i = 0; i < 5; i++) {
printf("%d ", countries[i]);
}

我的解答思路和尝试过的方法
我想要达到的结果

List of most populated countries

  1. Country: China, Population: 1439 million
  2. Country: United States, Population: 331 million
  3. Country: Brazil, Population: 212 million
  4. Country: Japan, Population: 126 million
  • 写回答

1条回答 默认 最新

  • CSDN专家-link 2021-12-06 17:27
    关注

    if (countries[j] > countries[j + 1])
    改为
    if (countries[j].population < countries[j + 1].population)
    temp改为struct Country 类型

    #include <stdio.h>
    #define COUNTRYNO 4
    struct Country {
        char country_name[50];
        int population;
    };
    void bubble_sort_countries(struct Country countries[COUNTRYNO],int n){
        int i,j;
        struct Country tmp;
        for (i = 0; i < n - 1; i++) {
            for (j = 0; j < n - i - 1; j++) {
                if (countries[j].population < countries[j + 1].population) {
                    tmp = countries[j];
                    countries[j] = countries[j + 1];
                    countries[j + 1] = tmp;
                }
            }
        }
    }
    
    int main( void ) 
    {
        int i=0;
        struct Country countries[COUNTRYNO] = 
        {
            { "United States", 331 },
            { "China", 1439 },
            { "Japan", 126},
            { "Brazil", 212 }
        };
        bubble_sort_countries(countries, COUNTRYNO);
        for (i = 0; i < COUNTRYNO; i++) {
            printf("Country: %s, Population: %d million\n", countries[i].country_name,countries[i].population);
    
        }
    
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 12月15日
  • 已采纳回答 12月7日
  • 创建了问题 12月6日