Problem with bubble sort
Nov 13, 2010 at 4:27am UTC
The sorting method works, I have used it without strcmp() for files of characters, but the file im sorting is array of chars, so I must use strcmp() and strcpy(), my only issue is that it sorts the files in reverse alphabetical order. Please shed some light on this if you can help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// sorts the cities in alphabetical order
void sortArrays( cityInfo cities[], int numCities )
{
char tempCityName[25];
int tempLowTemp, tempHighTemp;
bool swapped = true ;
int a = 0;
while (swapped)
{
swapped = false ;
a++;
for (int i=0; i < numCities - a; i++)
{
if ( strcmp( cities[i].cityName, cities[i+1].cityName ) < 0) // checks if first city is alphabetically lower than second city
{
strcpy( tempCityName, cities[i].cityName );
strcpy( cities[i].cityName, cities[i+1].cityName );
strcpy( cities[i+1].cityName, tempCityName ); // swaps cities in the array
tempLowTemp = cities[i].lowTemp;
cities[i].lowTemp = cities[i+1].lowTemp;
cities[i+1].lowTemp = tempLowTemp; // swaps low temp in array
tempHighTemp = cities[i].highTemp;
cities[i].highTemp = cities[i+1].highTemp;
cities[i+1].highTemp = tempHighTemp; // swaps high temp in array
swapped = true ;
}
}
}
}
Nov 13, 2010 at 4:28am UTC
wow duh, I just swapped the argument in the if statement to be greater than 0 and it solved my issue.
Topic archived. No new replies allowed.