I have written code for taking the input of the name, address, tariff, grade and number of rooms of any number of hotels. But now I'm stuck at a point where I have to take the input of a grade from the user and display the hotels in ascending order of price. I can successfully display the hotels of a given grade but I'm having trouble sorting the hotels according to price because this is the first time my code has gotten this long and confusing.
Here's my code so far:
#include <stdio.h>
#include <string.h>
//Structure definition starts
struct hotels
{
char name[25];
char address[300];
int grade, avgCharge, rooms;
};
//Structure definition over
//Main function starts
main()
{
int i, j, k, hotels, choice, grade, temp;
struct hotels a[50];
//Declaration part over---------------------------------------------------------------------------
printf("Enter the number of hotels\n");
scanf("%d", &hotels);
printf("\n\n");
//Taken number of hotels for upcoming loops-------------------------------------------------------
//for Loop for input of hotels and their details starts-------------------------------------------
for (i = 0; i < hotels; i++)
{
fflush(stdin);
printf("Enter the name of hotel %d\n", i + 1);
gets(a[i].name);
printf("\n");
printf("Enter the address of %s\n", a[i].name);
gets(a[i].address);
printf("\n");
printf("Enter the grade of the hotel from 1 to 5. (5 being the best)\n");
scanf("%d", &a[i].grade);
printf("\n");
printf("Enter the average charge per night of the hotel.\n");
scanf("%d", &a[i].avgCharge);
printf("\n");
printf("Enter the number of available rooms of the hotel.\n");
scanf("%d", &a[i].rooms);
printf("\n\n");
}
//Input part over, switch part starts-------------------------------------------------------------
printf("\n\n");
printf("Choose the task to perform-\n");
printf("1. Show hotels of a particular grade from low to high price.\n");
printf("2. Filter and show hotels under a particular tariff only.\n\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the grade of the hotel to apply the list filter.\n");
scanf("%d", &grade);
printf("The following hotels were found- \n\n");
for (i = 0; i < hotels; i++)
{
for (j = i + 1; j < hotels; j++) // Sorting according to price- Low to High
{
if (a[i].avgCharge > a[j].avgCharge)
{
temp = a[i].avgCharge;
a[i].avgCharge = a[j].avgCharge;
a[j].avgCharge = temp;
}
}
if (a[i].grade == grade) //Comparison for displaying the hotels of selected grade only.
{
printf("Hotel %d= %s\n", i + 1, a[i].name);
}
}
}
}
Now, this works as expected so far, I just can't figure out how to display the hotels in ascending order of price. Any help will be greatly appreciated. Thanks!