Reputation: 39
i need to sort flights in a program
H100.15005 SAT HOU 08:00 4 65.00
H111.15009 SAT HOU 17:00 10 65.00
im using bubble sort to make them in descending order for flight number my current program is
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;
}
}
}
}
currently the flights are not sorting. ive rechecked the for loops but cant figure it out
Upvotes: 1
Views: 70
Reputation: 3833
problems
- strcmp comparison direction
- index referencing with stcmp and inner loop ( need to reference j+1 and j not i.. )
adjusted code
#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;
}
output
$ ./sort_flights
==== input ====
0: H100.15005
1: H100.15009
==== output ====
0: H100.15009
1: H100.15005
reference
Upvotes: 1