Simple Algorithm (Sort)

So I wanted to get started on making algorithms and was advised to learn a simple sorting one. So That’s what I have done, below are two examples the top one takes the numbers (integers) 1, 100, 22, 33, 99, 10, 15, and puts them in order from low to high and the second code from high to low.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
    vector<int> values = {1, 100, 22, 33, 99, 10, 15};
    sort(values.begin(), values.end());
    
    for (int value : values)
        cout << value << endl;

    cin.get();
    return 0;

}

Console output is:

  • 1
  • 10
  • 15
  • 22
  • 33
  • 99
  • 100

High to low

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

int main(){
    vector<int> values = {1, 100, 22, 33, 99, 10, 15};
    sort(values.begin(), values.end(), greater<int>());
    
    for (int value : values)
        cout << value << endl;

    cin.get();
    return 0;
}

Console output:

  • 100
  • 99
  • 33
  • 22
  • 15
  • 10
  • 1

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *