书写冒泡排序功能

问题描述 投票:0回答:1

我正在尝试编写一个简单的冒泡排序函数来对一些随机数据进行排序。每当执行时,它只是打印最初编写时未排序的列表。我哪里做错了??? 代码:

#include <cs50.h>
#include <stdio.h>

#define NUM_CITIES 10

typedef struct
{
    string city;
    int temp;
}
avg_temp;

avg_temp temps[NUM_CITIES];

void sort_cities(void);

int main(void)
{
    temps[0].city = "Austin";
    temps[0].temp = 97;

    temps[1].city = "Boston";
    temps[1].temp = 82;

    temps[2].city = "Chicago";
    temps[2].temp = 85;

    temps[3].city = "Denver";
    temps[3].temp = 90;

    temps[4].city = "Las Vegas";
    temps[4].temp = 105;

    temps[5].city = "Los Angeles";
    temps[5].temp = 82;

    temps[6].city = "Miami";
    temps[6].temp = 97;

    temps[7].city = "New York";
    temps[7].temp = 85;

    temps[8].city = "Phoenix";
    temps[8].temp = 107;

    temps[9].city = "San Francisco";
    temps[9].temp = 66;

    sort_cities();

    printf("\nAverage July Temperatures by City\n\n");

    for (int i = 0; i < NUM_CITIES; i++)
    {
        printf("%s: %i\n", temps[i].city, temps[i].temp);
    }
}

void sort_cities(void)
{
    for (int i = 0; i < NUM_CITIES - 1; i++)
    {
        for (int j = 0; j < NUM_CITIES - i - 1; i++)
        {
            if (temps[j].temp < temps[j + 1].temp)
            {
                avg_temp initial = temps[j];
                temps[j] = temps[j + 1];
                temps[j + 1] = initial;
            }
        }
    }
}

我尝试过逻辑地思考事情,一步一步地对我来说是有意义的,我确实相信它被排序的功能,但也许不是我的主要功能?

c function bubble-sort
1个回答
0
投票
The logic for this is
for(i=0;i<n;i++)
{
    for(j=0;j<n-i-1;j++)
    {
       if([j]>array[j+1])
       {
         temp=array[j+1];
         array[j+1]=array[j];
         array[j]=temp;
       }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.