带有指针的冒泡排序在c中无法正常工作

时间:2017-03-12 07:54:17

标签: c arrays pointers bubble-sort

我已经创建了一个带指针的程序,程序工作正常,但冒泡排序功能不正常。有人可以帮助我并展示我做错了什么。在没有这个问题只是数组,但不知何故,它与指针不起作用。

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

1 个答案:

答案 0 :(得分:1)

你的问题是这段代码:

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

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

由于10是最高的数字,因此第一个外循环中不会有任何交换。因此,您可以打破外部循环,并将其余数字保留为未排序。

因此,请尝试删除上述代码。