Sort a Vector in Descending Order in C++



In C++, sorting a vector is a common task, and many problems are based on sorting. To sort a vector in descending order, we can use the std::sort() function from the STL (Standard Template Library). This function is included in the <algorithm> library. By default, std::sort() sorts in ascending order, but you can pass a custom comparator, such as std::greater<>(), to sort in descending order.

Here's a detailed overview of how sorting a vector works in C++ and what solutions we have provided in this article.

  • Default Sorting: We will use the std::sort() method that sorts in ascending order. To sort in descending order, we will usestd::greater<>() as a comparator.
  • Default Stable Sorting: Next, we will see the std::stable_sort() method, it is a stable sorting algorithm that maintains the relative order of equal elements. It is slightly slower than std::sort() because it guarantees stability and may use more memory.
  • Quick Sort: Then, we will let you know how to use QuickSort to sort a vector in descending order.

If you want to learn more about the differences between stable and unstable sorting algorithms, you can refer to this page. Besides std::sort() and std::stable_sort(), you can use other sorting algorithms to sort a vector in descending order. Those are given below -

Note: Both std::sort() and std::stable_sort() have a time complexity of O(n log n). However, std::stable_sort() is a bit slower because it guarantees stability and may use additional memory.

Using the in-built sort() Method

An unstable algorithm sorts the elements but doesn't consider the relative positions of equal elements, which may cause problems if you want to maintain the exact positions of equal elements.

Steps:

  • Declare a vector of integers and fill it with some values.
  • Print out the elements before sorting so we can see the difference between before and after sorting.
  • Call the std::sort() function with std::greater<>() as the third parameter to sort the vector in descending order.
  • Print the vector elements after sorting to see if we get the expected output.

Below is the C++ Code Example for sorting a vector in descending order -

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

using namespace std;

int main() {
   vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 };

   // Print elements before sorting
   cout << "Elements before sorting (Unstable algorithm):" << endl;
   for (const auto &i: v)
      cout << i << ' ' << endl;

   // Sorting in descending order
   sort(v.begin(), v.end(), greater<>());

   // Print elements after sorting
   cout << "Elements after sorting (Unstable algorithm):" << endl;
   for (const auto &i: v)
      cout << i << ' ' << endl;

   return 0;
}

Elements before sorting (Stable Sort) -

10 9 8 6 7 2 5 1 7 6

Elements after sorting (UnStable Sort) -

10 9 8 7 7 6 6 5 2 1

Time complexity: O(n log n)

Space complexity: O(n) (Auxiliary space)

Using the in-built stable_sort() Method

If you want to maintain the original order of equal elements, then std::stable_sort() is the method we can use. This function guarantees that elements with the same value will keep their original relative positions after sorting. It's a bit slower than std::sort() but is helpful when stability matters to solve a problem.

How to use Stable Algorithm:

  • Declare a vector of integers and fill it with some values.
  • Print out the elements before sorting so we can see the difference between before and after sorting.
  • Use std::stable_sort() function with std::greater<>() as the third parameter, to sort the vector in descending order while keeping the order of equal elements.
  • Print the vector elements after sorting to see if we get the expected output.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
   // Create and initialize a vector with some duplicate values
   vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1, 7, 6 };

   // Print elements before sorting
   cout << "Elements before sorting (Stable Sort):" << endl;
   for (const auto &i: v)
      cout << i << ' ' << endl;

   // Stable sort in descending order using greater
   stable_sort(v.begin(), v.end(), greater<>());

   // Print elements after sorting
   cout << "Elements after sorting (Stable Sort):" << endl;
   for (const auto &i: v)
      cout << i << ' ' << endl;

   return 0;
}

Elements before sorting (Stable Sort):

10 9 8 6 7 2 5 1 7 6

Elements after sorting (Stable Sort):

10 9 8 7 7 6 6 5 2 1

Time complexity: O(n log n)

Space complexity: O(n) (Auxiliary space)

Quick sort algorithm to sort a vector in descending order.

Now, let us see how we can sort a vector in descending order using the QuickSort algorithm. We will explain how the QuickSort algorithm works for sorting a vector in descending order by providing detailed steps and an explanation.

Steps:

  • Take a pivot: Select the last element of the current subarray as the pivot. Pivot will help in partitioning the array.
  • Partitioning the array: We need to rearrange the elements in such a way that all elements greater than the pivot come before it, and elements smaller than the pivot come after it. This helps to know if the pivot is in its correct position for descending order.
  • Recursive Sort: We will recursively apply the QuickSort algorithm to the left and right subarrays (those before and after the pivot), we will continue to choose pivots and partition the array until the entire vector is sorted.
  • Base Case: When our subarray has zero or one element, we need to stop the recursion because the subarray is already sorted.

The following is the code to sort a vector in descending order using QuickSort -

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

// Partition function for QuickSort
int partitionFun(vector<int>& v, int low, int high) {
int pivot = v[high]; // Set the last element as the pivot
  int i = low - 1; // Initialize the pointer for greater elements
  for (int j = low; j < high; ++j) {
     if (v[j] > pivot) { // Compare to sort in descending order
        swap(v[++i], v[j]); // Swap elements if they are greater than the pivot
    }
}
   swap(v[i + 1], v[high]); // Place pivot in its correct position
   return i + 1; // Return the pivot index
}

    // QuickSort function
void quickSortDescendingOrder(vector<int>& v, int low, int high) {
   if (low < high) {
      int prt = partitionFun(v, low, high); // Partition the vector
        quickSortDescendingOrder(v, low, prt - 1); // Sort the left subarray
        quickSortDescendingOrder(v, prt + 1, high); // Sort the right subarray
    }
}

// Main function
int main() {
   vector<int> v = {64, 34, 25, 12, 22, 11, 90}; // Initialize the vector
   quickSortDescendingOrder(v, 0, v.size() - 1); // Call QuickSort to sort the vector in descending order
   for (int i : v) cout << i << " "; // Print the sorted vector
      return 0;
}

The above code sorts a vector in descending order using the QuickSort algorithm:

  • Partition Function: This function selects the pivot (last element) and rearranges the vector in such a way that all elements greater than the pivot will be on the left. It helps to place the pivot in its correct position in the sorted order and returns the pivot index.
  • QuickSort Function: This function recursively sorts the left and right parts of the vector based on the pivot element. It calls the partition function and applies QuickSort to the left and right subarrays until all elements are sorted.
  • Main Function: In the main function, we initialize a vector and call the QuickSort function to sort the vectors in descending order. Then we print the sorted vectors on the console.

Output:

90 64 34 25 22 12 11

Time Complexity: O(n log n)

Space Complexity: O(log n) (Auxiliary space)

Updated on: 2024-11-22T11:21:24+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements