Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sort() for descending instead of ascending C++

I am trying to sort the user given row or column of a 2d array. The code I have can sort in ascending order but not descending.

void sortArray(int arr[12][12], int index, int row)
{
   if (row == 0)
   {
       sort( arr[index] , arr[index] + 12);
   }
   else 
   {
       int tempArr[12];
       getColArr(arr, tempArr, index);
       sort(tempArr, tempArr + 12);
       for (int i = 0; i < 12; i++)
       {
           arr[i][0] = tempArr[i];
       }
   }
}

How do I change it into descending?

like image 683
Pfy1919 Avatar asked Feb 11 '23 02:02

Pfy1919


2 Answers

Use std::greater as third parameter of std::sort

std::sort(begin(vec), end(vec),std::greater<int>());

FYI..when you use std::sort without third parameter, third parameter is defaulted with std::less.

like image 144
Steephen Avatar answered Feb 12 '23 16:02

Steephen


You can use reverse iterators rbegin and rend, example:

int main()
{
    int vec[6] {1,2,3,4,5,6};
    sort(rbegin(vec), rend(vec));

    for (const auto &i : vec) 
        cout << i << " ";
}

output: 6 5 4 3 2 1

Or you may use a lambda as the third argument to sort:

int vec[6] = {1,2,3,4,5,6};
sort(vec, vec+6, [](int i, int j){return i>j;});

If you don't have a compiler that supports C++11 or C++14, you can create your own compare function and pass it as third argument to sort:

bool isGreater(int i, int j)
{
    return i > j;
}

int main()
{
    int vec[6] = {1,2,3,4,5,6};
    sort(vec, vec+6, isGreater);

    for (int i = 0; i != 6; ++i)
        cout << vec[i] << " ";
}

Output: 6 5 4 3 2 1

like image 41
Andreas DM Avatar answered Feb 12 '23 16:02

Andreas DM