include iostream include algorithm using namespace std struct book cha

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <algorithm>
using namespace std;
struct book {
char name[100];
int year;
};
int compare(const void *a, const void *b) {
book *book1 = (book *) a;
book *book2 = (book *) b;
return (book2->year - book1->year);
}
int main() {
size_t dimension;
printf("Enter the dimension of books array: ");
cin >> dimension;
struct book books[dimension];
string query;
for (int i = 0; i < dimension; ++i) {
cout << "Enter name of the book" << endl;
cin >> books[i].name;
cout << "Enter year of the book" << endl;
cin >> books[i].year;
}
cout << "Entered array:" << endl;
for (int i = 0; i < dimension; ++i) {
cout << books[i].name << " - " << books[i].year << endl;
}
qsort(books, dimension, sizeof(book), compare);
cout << "Sorted array:" << endl;
for (int i = 0; i < dimension; ++i) {
cout << books[i].name << " - " << books[i].year << endl;
}
return 0;
}