【问题标题】:Bubble sort with pointers in c not working properlyc 中带有指针的冒泡排序无法正常工作
【发布时间】:2017-03-12 07:54:16
【问题描述】:

我创建了一个带有指针的程序,该程序运行良好,但是冒泡排序无法正常运行。有人可以帮助我并显示我做错了什么。 In 只是数组没有这个问题,但不知何故它不能很好地使用指针。

#include <stdio.h>
#include <ctype.h>

main()
{
// Initializing pointer arrays
int i;
int ctr = 0;
char ans;
char * movies[5] = {"John Wick 2", "Kong: Skull Island", "Justice League",
                    "Mummies", "Thor: Ragnarok"};
int movierate[5];
int outer, inner, didSwap, temprate;
char * tempmovies = "This will be used to sort rated movies";

printf("***Oscar Movie Rating***\n");
printf("Time to rate this years best picture.\n");
for(i = 0; i < 5; i++)
{
    printf("\nHave you seen %s?", movies[i]);
    scanf(" %c", &ans);
    if((toupper(ans)) == 'Y')
    {
        printf("Please rate the movie on a scale from 1-10. ");
        scanf(" %d", &movierate[i]);
        ctr++;
        continue;
    }
    else
    {
        movierate[i] = -1;
    }
}
for(outer = 0; outer < 4; outer++)
{
    didSwap = 0;
    for(inner = outer; inner < 5; inner++)
    {
        if(movierate[inner] > movierate[outer])
        {
            tempmovies = movies[inner];
            temprate = movierate[inner];
            movies[inner] = movies[outer];
            movierate[inner] = movierate[outer];
            movies[outer] = tempmovies;
            movierate[outer] = temprate;
            didSwap = 1;
        }
    }
    if(didSwap == 0);
    {
        break;
    }
}
for(i = 0; i < ctr; i++)
{
    printf("\n%s rated a %d!", movies[i], movierate[i]);
}
return (0);
}

【问题讨论】:

  • main() 不是主函数的有效原型。符合标准的int main(void)int main(int, char**)。任何以其他方式进行教学的人都是在损害您的利益。
  • @StoryTeller 谢谢,我会检查差异
  • 输入?预期输出?实际输出?
  • @StoryTeller 输入:约翰威克 9,骷髅岛 7,正义联盟 10,木乃伊 8,雷神 5 - 预期输出:从高到低排序 - 实际输出:正义联盟 10,骷髅岛 7,约翰威克 9,木乃伊 8,雷神 5
  • 标记了错误的人

标签: c arrays pointers bubble-sort


【解决方案1】:

你的问题是这段代码:

if(didSwap == 0);
{
    break;
}

考虑对这些数字进行排序:10 1 2 3 4

由于10 是最大的数字,所以在第一个外循环中不会有任何交换。因此,您跳出外循环,其余数字未排序。

所以只需尝试删除上面的代码。

【讨论】:

  • 谢谢你的帮助,确实是这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多