include iostream include algorithm using namespace std struct book str

 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
#include <iostream>
#include <algorithm>
using namespace std;
struct book {
string name;
int price;
};
int compare(const void *a, const void *b) {
book *book1 = (book *) a;
book *book2 = (book *) b;
return (book1->price - book2->price);
}
int main() {
size_t dimension = 3;
cout << "Enter 3 books for sorting: " << endl;
struct book books[dimension];
string query;
for (int i = 0; i < dimension; ++i) {
cout << "Enter name of the book[" << i << "]" << endl;
cin >> books[i].name;
cout << "Enter price of the book" << i << "]" << endl;
cin >> books[i].price;
}
cout << "Entered array:" << endl;
for (int i = 0; i < dimension; ++i) {
cout << books[i].name << " - " << books[i].price << endl;
}
qsort(books, dimension, sizeof(book), compare);
cout << "Sorted array by price:" << endl;
for (int i = 0; i < dimension; ++i) {
cout << books[i].name << " - " << books[i].price << endl;
}
return 0;
}