Sort Items In Array By Desc In C++
Code snippet for how to Sort Items In Array By Desc In C++ with sample and detail explanation
Sorting items in an array in descending order is a fundamental concept in C++ programming. It forms the basis of different algorithms and data manipulation techniques in computer science. This article will guide you through a step-by-step tutorial on how to perform this task.
Code Snippet for Sorting Items in Array By Desc
Here is a simple C++ code snippet that sorts an array in descending order using the sort() function from the algorithm library.
#include <iostream>
#include <algorithm> //for sort() function
using namespace std;
bool descending (int i, int j) { return i > j; } // comparator function
int main() {
int array[5] = {3, 2, 5, 1, 4};
sort(array, array+5, descending);
for(int i = 0; i<5; i++) {
cout << array[i] << " ";
}
return 0;
}
This code will output: 5 4 3 2 1
.
Code Explanation for Sorting Items in Array By Desc
Let’s break down the code to further understand how it works:
- Including the necessary libraries: The
<algorithm>
library is included to use thesort()
function and the<iostream>
for input/output operations.
#include <iostream>
#include <algorithm>
- Comparator function: This function,
descending(int i, int j)
, is a custom function that we pass to thesort()
function to carry out the sorting in descending order. It returns true if ‘i’ is greater than ‘j’, effectively ordering our array from highest to lowest.
bool descending (int i, int j) { return i > j; }
- Declaring the array: Next, we declare and initialize the array which we will be sorting. In this case, we have an array of integers.
int array[5] = {3, 2, 5, 1, 4};
- Using the sort() function: The
sort()
function takes three parameters. The first two pointers point to the beginning and just past the end of the array segment to be sorted, and the third is our comparator function.
sort(array, array+5, descending);
- Printing the array: After sorting the array in descending order, we use a for loop to print out all the items in the array.
for(int i = 0; i<5; i++) {
cout << array[i] << " ";
}
Following this tutorial, you should now have a clearer understanding of how to sort items in an array in descending order in C++. This fundamental skill forms the basis of various algorithmic and data manipulation problems in the field of programming.