Sorting Array Elements in C++

In this tutorial of our C++ course, we will learn how to order the elements of an Array.

Sort elements (sorting)

Sorting, that is, placing elements (such as numbers) in a certain order (such as increasing or decreasing, for example), is one of the most important and studied subjects in computing, due to its importance.

At your school or university, the list of students is sorted alphabetically.
The polling stations where you are going to vote also use some kind of order.
Bank accounts also organize everything according to numbers, as well as the numbers on a lottery card.
When you are a professional C++ programmer, your company will ask you to organize several things, in some kind of order, such as names, salaries, identifications, positions, size or weight of products, etc. etc.

That is, it is an absurdly used subject, too important indeed, that you will use a lot, several times, in your career, and we will introduce now in this tutorial, a little of the subject.

How to sort an Array in C ++

We will use the Selection Sort algorithm to order the elements of the Array.
First, we created the gen() function, which will generate random numbers from 1 to 100.

Let's create an array of size=10 and name 'num'.

We will then fill each position in this array with a random number, and then print this array of random values. Next step now is to order this array,

The logic is as follows: we take the first element of the array, and compare it with all the others. That is, we compare element 0 with index 1, then 0 with index 2 ... until it reaches 0 with index 9.
If these other elements are less than index 0, we invert the values ​​of these two elements. Okay, at the end of this operation, the lowest value of the array will be at position 0.

Now we are going to place the second smallest value at index position 1.
For this, we will compare element 1 with 2, then 3, then 4 ... until we compare element 1 with element 9, the last. Again, if this other element is less than index 1, we invert their position.

At the end of this step, the second lowest value will be in position 1. Now just do this for elements 2, 3, ... 7 and 8. In the last 'round' of comparisons, we compare element 8 with 9 to decide which is bigger and which is smaller.

The first looping, using a for loop, is what controls the first element, and inside it we are going to compare with all the other indexes.
We will use the 'prev' variable to receive the first index. It ranges from 0 to 'size-2' (from 0 to 8, that is: for (prev=0; prev<size -1; prev++)).

The second loop, a nested loop, will compare the 'prev' index with all the other elements in the array.
The second index will be stored in the variable 'next', it always starts with the value 'prev + 1' (when the first element is 0, it starts from 1 ... when the first element is index 1, it starts at index 2, etc etc ... until the first element is index 8 and it will be index 9), until 'size-1' (ie for (next=prev+1; next<size; next++) ) .

Within this inner loop, we use an IF conditional test to find out if the second element is less than the first, if it is, we invert the values ​​of these elements.

See how our code looks:
#include <iostream>
#include <random>
using namespace std;

int gen()
{
    std::random_device rd;
    std::mt19937 gen_numb(rd());
    std::uniform_int_distribution<> dis(1, 100);

    return dis(gen_numb);
}

int main()
{
    int size=10, prev, next, aux;
    int num[size];

    for(aux=0 ; aux<size ; aux++){
        num[aux] = gen();
    }

    cout<<"Original Array: "<<endl;
    for(aux=0 ; aux<size ; aux++)
        cout<<num[aux]<<" ";
    cout<<endl;

    // Selection sort algorithm
    for(prev=0 ; prev<size-1 ; prev++)
        for(next=prev+1 ; next<size ; next++){
            aux=num[prev];

            if(num[next]<num[prev]){
                num[prev]=num[next];
                num[next] = aux;
            }
        }

    cout<<"Ordered Array: "<<endl;
    for(aux=0 ; aux<size ; aux++)
        cout<<num[aux]<<" ";
    cout<<endl;

    return 0;
}

Array Exercises

01. Make an algorithm that orders the elements of an array from major to minor, that is, decreasing order.

02. Place the previous code inside functions: function that fills the array, function that inverts two values, function that makes the selection sort and function that displays arrays. Use function prototypes, to make your code very professional.

Solution in the e-book

No comments:

Post a Comment