Reputation: 97
I've done a bit of code to try and sort my list of movies by either year, name or votes however when I run the application it does not sort. Just wondering where I went wrong. I believe it might have something to do with Movie movie.
UPDATE: I've fixed it somewhat, now it is sorting the first 10 or 20 items on the list but will not sort the rest. I've checked with cout if there was anything wrong with my loops and it seems to go from 0-248 fine.
enum MovieSortOrder
{
BY_YEAR = 0,
BY_NAME = 1,
BY_VOTES = 2
};
int Movie::CompareByVotes(Movie m) {
if (m.get_votes() == this->get_votes()) {
return 0;
} else if (m.get_votes() > this->get_votes()) {
return 1;
} else {
return -1;
}
}
int Movie::CompareByYear(Movie m) {
if (m.get_year() == this->get_year()) {
return 0;
} else if (m.get_year() > this->get_year()) {
return 1;
} else {
return -1;
}
}
int Movie::CompareByName(Movie m) {
string a = m.get_name();
string b = this->get_name();
if (a[0] = b[0]) {
return 0;
} else if (a[0] > b[0]) {
return 1;
} else if (a[0] < b[0]) {
return -1;
}
}
int Movie::CompareTo(Movie m, MovieSortOrder n) {
if (n == 0) {
return CompareByYear(m);
} else if (n == 1) {
return CompareByName(m);
} else if (n == 2) {
return CompareByVotes(m);
}
}
bool MovieList::MoveLargestToEnd(MovieSortOrder n) {
bool changed = false;
for (int i = 0; i < last_movie_index; i++) {
//cout << i << endl;
if (movies->CompareTo(movies[i], n) > movies->CompareTo(movies[i + 1], n)) {
swap(movies[i], movies[i + 1]);
changed = true;
}
}
return changed;
}
void MovieList::BubbleSort(MovieSortOrder n) {
for (int i = 0; i < last_movie_index; i++) {
if (!MoveLargestToEnd(n)) {
return;
}
}
}
Upvotes: 4
Views: 121
Reputation: 20858
You're likely accessing an out-of-bound index i
here:
for (int i = 0; i < last_movie_index; i++)
{
if (movie.CompareTo(movies[i], n) > movie.CompareTo(movies[i + 1], n))
{
swap(movies[i], movies[i + 1]);
changed = true;
}
}
Also, MovieList::BubbleSort
can be simplified to just:
void MovieList::BubbleSort(MovieSortOrder n)
{
while (MoveLargestToEnd(n));
}
More problematic parts of your code:
if (movie.CompareTo(movies[i], n) > movie.CompareTo(movies[i + 1], n))
Given how you've implemented those comparision functions, your usage above is incorrect. You're creating an empty Movie movie;
variable and you're comparing that against your movies[i]
. That's a big reason why your sort isn't working. What you really want is to compare adjacent items in your movies
list. Something like:
if (movies[i].CompareTo(movies[i + 1], n) == -1)
Upvotes: 0
Reputation: 57784
This line is a problem:
if (a[0] = b[0])
It does assignment, not comparison. Its true/false comes from the value of b[0]
.
That is the first if
in Movie::CompareByName(Movie m)
Upvotes: 2