我需要在程序中对航班进行分类
H100.15005 SAT HOU 08:00 4 65.00
H111.15009 SAT HOU 17:00 10 65.00
我使用冒泡排序按降序排列航班号 我目前的计划是
void sortFlights(Flight flightM[], int iFlightCnt)
{
Flight temp;
int i, j, bChange = 1;
for (i = 0; i < (iFlightCnt - 1) && bChange == 1; i++)
{
bChange = 0;
for (j = 0; j < (iFlightCnt - i - 1); j++)
{
if (strcmp(flightM[i + 1].szFlightId, flightM[i].szFlightId) < 0)
{
temp = flightM[i];
flightM[i] = flightM[i + 1];
flightM[i + 1] = (Flight)temp;
bChange = 1;
}
}
}
}
目前航班没有排序。我已经重新检查了for循环,但无法弄清楚
答案 0 :(得分:1)
<强>问题强>
- strcmp 比较方向
- 使用stcmp和内部循环引用索引(需要引用j + 1而j不是i ..)
调整后的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* stub structure to replicate problem */
typedef struct
{
char szFlightId[11];
}Flight;
void sortFlights(Flight flightM[], int iFlightCnt)
{
Flight temp;
int i, j, bChange = 1;
for (i = 0; i < (iFlightCnt - 1) && bChange == 1; i++)
{
bChange = 0;
for (j = 0; j < (iFlightCnt - i - 1); j++)
{
if (strcmp(flightM[j + 1].szFlightId, flightM[j].szFlightId) > 0)
/* change: reference j+1,
direction of strcmp comparison for desired sort order */
{
temp = flightM[j];
flightM[j] = flightM[j + 1]; /* change: reference j+1 */
flightM[j + 1] = (Flight)temp; /* change: reference j+1 */
bChange = 1;
}
}
}
}
/* convenience output function */
void printFlights(Flight *flightM, int iFlightCnt)
{
int index;
for(index = 0; index < iFlightCnt; index++)
{
printf("%d: %s\n", index, flightM[index].szFlightId);
}
}
int main(void)
{
Flight flightM[2];
sprintf(flightM[0].szFlightId, "H100.15005");
sprintf(flightM[1].szFlightId, "H100.15009");
printf("==== input ====\n");
printFlights(flightM, 2);
sortFlights(flightM, 2);
printf("\n");
printf("==== output ====\n");
printFlights(flightM, 2);
return 0;
}
<强>输出强>
$ ./sort_flights
==== input ====
0: H100.15005
1: H100.15009
==== output ====
0: H100.15009
1: H100.15005
<强>参考强>