我的冒泡排序有什么问题?

时间:2016-10-23 02:07:51

标签: c

此代码初始化一个包含9个值(电影名称)的指针数组,然后鼓励用户输入每个电影的评级。在为每部电影输入评级之后,应该使用冒泡排序代码将每部电影从最低到最高排序。最后,电影列表应按照从最低到最高的顺序打印出来。不幸的是,代码的最后一部分是打算按照评级的顺序打印出电影不起作用。这是为什么?

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]);
}

1 个答案:

答案 0 :(得分:0)

您按升序对movieratings数组进行排序,并从头开始打印ctr元素,以便打印评分最低的电影。 按降序对数组进行排序,即将此if (movieratings[i] > movieratings[i+1])更改为if (movieratings[i] < movieratings[i+1])