Javatpoint Logo
Javatpoint Logo

C++ Program To Sort An Array In Descending Order

Sorting an array in descending order is a common task that can be accomplished in various ways using the C++ programming language. This tutorial will discuss two methods for sorting the array in descending order.

1. Method 1:

Output:

C++ Program To Sort An Array In Descending Order

Explanation:

This program creates an array of 10 integers and uses the sort function from the C++ Standard Template Library (STL) to sort the array in descending order. The sort function takes three arguments: the first and second arguments specify the range of elements to be sorted, and the third argument is a comparison function that determines the order in which the elements are sorted. In this case, we are using the greater<int> comparison function, which compares two integers and returns true if the first integer is greater than the second.

2. Method 2:

Selection sort is an in-place sorting algorithm that works by iteratively selecting the next smallest element and swapping it with the current element until the array is sorted. While it is not the most efficient sorting algorithm in terms of time complexity, it is simple to implement and useful for sorting small arrays or as a learning exercise.

Here is the general structure of a selection sort function in C++:

To sort the array in descending order, we can reverse the comparison operator in the if statement from < to >. This will cause the selection sort function to select the maximum element in the unsorted portion of the array at each iteration instead of the minimum element.

Here is the modified selection sort function for sorting an array in descending order:

To test our sorting Function, we can create a simple program that generates an array of random integers, prints it to the console, sorts it in descending order using the selectionSortDescending Function, and then prints the sorted array to the console.

Here is an example program that demonstrates how to use the selectionSortDescending Function to sort an array in descending order:

Output:

C++ Program To Sort An Array In Descending Order

Explanation:

This program will generate an array of 10 random integers, print it to the console, sort it in descending order using the selectionSortDescending Function, and then print the sorted array to the console.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA