Advertisement
bogdanNiculeasa

Sorting

Jan 12th, 2021
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <iostream>
  2. #include <string.h>
  3. #include<limits>
  4.  
  5.  
  6. using namespace std;
  7.  
  8. struct Book {
  9.     char title[50];
  10.     char author[50];
  11.     int isbn;
  12.     int publishingYear;
  13. };
  14.  
  15.  
  16. int main() {
  17.  
  18.     // Create a program which sorts an array of books based on publishing year, descending
  19.  
  20.     struct Book books[3];
  21.     int n = 2;
  22.     for(int i = 0; i < n; i++) {
  23.  
  24.  
  25.         cout << "Enter title: ";
  26.         cin.getline(books[i].title, 50);
  27.  
  28.         cout << "\nEnter author: ";
  29.         cin.getline(books[i].author, 50);
  30.  
  31.         cout << "\nEnter publishing year: ";
  32.         cin >> books[i].publishingYear;
  33.         cin.ignore(numeric_limits<streamsize>::max(),'\n');
  34.  
  35.         cout << "\nEnter isbn: ";
  36.         cin >> books[i].isbn;
  37.         cin.ignore(numeric_limits<streamsize>::max(),'\n');
  38.  
  39.     }
  40.  
  41.     cout << "===============================\n";
  42.     cout << "Books before sorting: \n\n";
  43.     cout << "Author\tTitle\tISBN\t#Publishing Year\n";
  44.     for(int i = 0; i < n;i++) {
  45.         cout <<books[i].author <<"\t" << books[i].title << "\t" << books[i].isbn << "\t" << books[i].publishingYear;
  46.         cout << endl;
  47.     }
  48.  
  49.     for(int i = 0; i < n; i++) {
  50.         for(int j = 0; j < n-1;j++) {
  51.             if(books[j].publishingYear < books[j+1].publishingYear) {
  52.                 struct Book aux = books[j];
  53.                 books[j] = books[j+1];
  54.                 books[j+1] = aux;
  55.             }
  56.         }
  57.     }
  58.     cout << "===============================\n\n";
  59.  
  60.     cout << "Books after sorting: \n\n";
  61.     cout << "Author\tTitle\tISBN\t#Publishing Year\n";
  62.     for(int i = 0; i < n;i++) {
  63.         cout <<books[i].author <<"\t" << books[i].title << "\t" << books[i].isbn << "\t" << books[i].publishingYear;
  64.         cout << endl;
  65.     }
  66.  
  67.     return 0;
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement