OneBite.Dev - Coding blog in a bite size

Sort Items In Array By Asc In C++

Code snippet for how to Sort Items In Array By Asc In C++ with sample and detail explanation

Sorting an array in ascending order is one of the fundamental tasks in the field of programming. Understanding this, especially in a language like C++, is a vital skill for any aspiring computer scientist or software engineer.

Code Snippet: Sorting Array In Ascending Order

Here’s a simple and straightforward code snippet in C++ to sort an array in ascending order:

#include<iostream>
#include<algorithm>
using namespace std;

int main() {
    int arr[] = {10,30,20,5,25};
    int n = sizeof(arr)/sizeof(arr[0]);
    
    sort(arr, arr+n);
    
    for(int i=0; i<n; i++)
        cout << arr[i] << " ";
        
    return 0;
}

Code Explanation: Sorting Array In Ascending Order

In this tutorial, we will break down each step to understand how this program works and how it sorts an array.

First, we include the necessary headers:

#include<iostream>
#include<algorithm>
using namespace std;

We require <iostream> for input/output operations and <algorithm> for the sort() function.

Next, we declare the main function and define our array and calculate its size:

int main() {
    int arr[] = {10,30,20,5,25};
    int n = sizeof(arr)/sizeof(arr[0]);

Here, arr[] is the array we wish to sort and n is the size of the array, computed by dividing the total size of the array by the size of a single element.

Now we get into the actual sorting:

    sort(arr, arr+n);

The sort() function is a standard library function in C++ that sorts all elements in an array. The operation arr+n gives the address one past the end of the array, which is a standard way to represent ranges in C++.

Lastly, we print out all elements of the now sorted array and return 0 indicating that the program has executed successfully:

    for(int i=0; i<n; i++)
        cout << arr[i] << " ";
        
    return 0;
}

The for loop iterates through each element in the array and prints it.

And there you have it, a simple and effective way to sort items in an array by ascending order in C++.

c-plus-plus