sorting txt.file

i need to sort a text file (it could be increasing or decreasing) years.
the text file includes
#of entries
nameofwar: year\n
how can I sort the text file with out the use of vectors, algorithms.
for (int i=0; i<sizxefile;i++) //i know to run a for loop to go over the entire file
//and to print it would be
cout<<array[i].title<<":"<<array[i].year:
but how do I print them pout in order?
thank you so much in advance!
Last edited on
how can I sort the text file with out the use of vectors?

What do vectors have to do with this?

1
2
std::sort( array, array+sizxefile,
   [](const auto& lhs, const auto& rhs){ return lhs.year < rhs.year; } );

The operator (in bold) is the only thing to change, if you want descending rather than ascending order.

See: http://www.cplusplus.com/reference/algorithm/sort/
I meant algorithms I apologize; I am not allowed to use a library to sort the data.
how can I sort the text file with out the use of vectors, algorithms.

You create a struct to hold your data. Selection sort an array (this does it in decreasing order):
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
#include <iostream>

// a reverse selection sort
void ReverseSort(int a[], int n)
{
   for (int i = 0; i < n - 1; i++)
   {
      int max = i;

      for (int j = i + 1; j < n; j++)
      {
         if (a[j] > a[max]) // normal selection sort comparison is <
         {
            max = j;
         }
      }

      int temp = a[i];
      a[i]     = a[max];
      a[max]   = temp;
   }
}

int main()
{
   const int arrSize = 7;

   int arr[arrSize] { 20, 8, 6, 5, 3, 12, 15 };

   for (int i = 0; i < arrSize; i++)
   {
      std::cout << arr[i] << ' ';
   }
   std::cout << '\n';

   ReverseSort(arr, arrSize);

   for (int i = 0; i < arrSize; i++)
   {
      std::cout << arr[i] << ' ';
   }
   std::cout << '\n';

   std::cout << arr[0] << ' ' << arr[1] << ' ' << arr[2] << '\n';
}

You modify the code to suit your requirements.

Topic archived. No new replies allowed.