Zen Mournster Zen Mournster - 1 month ago 14
C Question

What is wrong with my bubble sort?

This code initialises an array of pointers with 9 values (names of movies), then the user is encouraged to enter a rating for each movie. After the rating has been entered for each movie, a bubble sort code is supposed to sort each movie from lowest to highest. Finally, the list of movies is supposed to be printed out in the order of lowest to highest. Unfortunately, the last part of the code which is meant to print out the movies in the order of their rating doesn't work. Why is this?

int i;
int ctr = 0;
char ans;
char * movies[9] = {"Amour", "Argo","Beasts of the Southern Wild","Django Unchained","Les Miserables","Life of Pi", "Lincoln","Silver Linings Playbook","Zero Dark Thirty"};
int movieratings[9];
char *tempmovie ;
int didSwap, temprating;

printf("\n\n*** Oscar Season 2012 is here and the nominees are: ***\n\n");

for (i=0;i<9;i++)//FOR LOOP TO PRINT OUT VALUES IN movies
{
printf(" %s\n",movies[i]);
}
printf("Time to rate this year's best picture nominees:");

for (i=0; i< 9; i++)//for loop to rate movies
{
printf("\nDid you see %s? (Y/N): ", movies[i]);
scanf(" %c", &ans);

if ((toupper(ans)) == 'Y')

{
printf("\nWhat was your rating on a scale of 1-10:");
scanf(" %d", &movieratings[i]);
ctr++;//counter to recognise how many movies you have seen
continue;
}

else
{
movieratings[i] = -1;
}
}

// Now sort the movies by rating (the unseen will go
// to the bottom)

while(1)//bubble sort to sort movies by rating
{
didSwap = 0;
for (i = 0; i < 9; i++)
{
if (movieratings[i] > movieratings[i+1])
{
tempmovie = movies[i];
temprating = movieratings[i];
movies[i] = movies[i+1];
movieratings[i] = movieratings[i+1];
movies[i+1] = tempmovie;
movieratings[i+1] = temprating;
didSwap = 1;
}
}
if (didSwap == 0)
{
break;
}
}


printf("\n\n** Your Movie Ratings for the 2012 Oscar Contenders **\n");

for (i=0; i<ctr; i++)
{
printf("%s rated a %d \n", movies[i], movieratings[i]);
}

Answer

You are sorting the movieratings array in ascending order and printing ctr elements from the beginning so it prints the movies with lowest rating. sort the array in descending order i.e change this if (movieratings[i] > movieratings[i+1]) to if (movieratings[i] < movieratings[i+1])

Comments