#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char title[100];
float imdbRating;
int releaseYear;
int popularity; // number of views/watch time popularity
} Movie;
// Global variable to store sort choice
int sortChoice;
// Swap function
void swap(Movie *a, Movie *b) {
Movie temp = *a;
*a = *b;
*b = temp;
}
// Comparison function based on user choice
int compare(Movie a, Movie b) {
if (sortChoice == 1) { // Sort by IMDB Rating (desc)
return (a.imdbRating < b.imdbRating);
} else if (sortChoice == 2) { // Sort by Release Year (desc)
return (a.releaseYear < b.releaseYear);
} else { // Sort by Popularity (desc)
return (a.popularity < b.popularity);
}
}
// Partition function for QuickSort
int partition(Movie arr[], int low, int high) {
Movie pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (compare(arr[j], pivot)) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
// QuickSort function
void quickSort(Movie arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int n;
printf("Enter number of movies: ");
scanf("%d", &n);
Movie *movies = (Movie *)malloc(n * sizeof(Movie));
if (!movies) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter movie details (Title Rating Year Popularity):\n");
for (int i = 0; i < n; i++) {
scanf("%s %f %d %d", movies[i].title, &movies[i].imdbRating, &movies[i].releaseYear, &movies[i].popularity);
}
printf("\nSort by:\n1. IMDB Rating\n2. Release Year\n3. Popularity\nEnter choice: ");
scanf("%d", &sortChoice);
quickSort(movies, 0, n - 1);
printf("\nSorted Movies:\n");
printf("%-20s %-12s %-12s %-12s\n", "Title", "Rating", "Year", "Popularity");
for (int i = 0; i < n; i++) {
printf("%-20s %-12.1f %-12d %-12d\n", movies[i].title, movies[i].imdbRating, movies[i].releaseYear, movies[i].popularity);
}
free(movies);
return 0;
}