Diego Franco
Diego Franco

Reputation: 73

Bubble sort with pointers in c not working properly

I've created a program with pointers, the program works fine, however the bubble sort isn't functioning properly. Can someone assist me and show what I am doing wrong. In didn't have this problem with just arrays, but somehow it doesn't function well with pointers.

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

Upvotes: 0

Views: 79

Answers (1)

4386427
4386427

Reputation: 44284

Your problem is this code:

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

Consider sorting these numbers: 10 1 2 3 4

Since 10 is the highest number, there will not be any swap in the first outer-loop. Consequently you break out of the outer-loop and leaves the rest of the numbers unsorted.

So just try to remove the above code.

Upvotes: 1

Related Questions