2

I am trying to sort a c++ subarray by first element. My code is currently set up like this:

int umbrellas[3][2] = {{5, 6}, {2, 7}, {9, 20}};

int n = sizeof(umbrellas) / sizeof(umbrellas[0]);

sort(umbrellas, umbrellas + n, greater<int>());

The sort function doesn't seem to be functioning properly and when I run the code it generates errors. Is there a way to sort the array from

{{5, 6}, {2, 7}, {9, 20}}

into

{{2, 7}, {5, 6}, {9, 20}}

?

Redz
  • 324
  • 1
  • 4
  • 16
  • 1
    Does this answer your question? [Sort a 2D array in C++ using built in functions(or any other method)?](https://stackoverflow.com/questions/20931669/sort-a-2d-array-in-c-using-built-in-functionsor-any-other-method) – thedemons Jul 02 '22 at 00:52

2 Answers2

1

Use a std::vector of std::vector as your container and the sort becomes much easier to do with. Not only is std::vector the preferred container for C++ but using STL functions on it is way simpler and direct , without any substantiable overhead.

Define your data as

std::vector<std::vector<int>> umbrellas{
    {5, 6},
    {2, 7},
    {9, 20}
};

Now you can use a custom comparator lambda that takes in two vector element references and returns True when the first element of the above vector is smaller than that of the one below.

std::sort(umbrellas.begin(),
          umbrellas.end(),
          [](const std::vector<int> &above, const std::vector<int> &below)
          {
              return (above[0] < below[0]);
          });

And the output :

for (auto &&row : umbrellas) {
    for (auto element : row) {
        std::cout<< element<< " ";
    }
    std::cout<< "\n";
}
2 7 
5 6 
9 20

Taking this to C++20 it's even easier:

std::ranges::sort(umbrellas, std::less(),
     [](const auto &v) { return v[0];});
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42
0

If time complexity doesn't matter, this code will achieve the desired with O(n^2) complexity

int arr[3][2] = {{5, 6}, {2, 7}, {9, 20}};

int n = sizeof(arr) / sizeof(arr[0]);

for(int i = 0 ; i < n - 1; i++){
    for(int j = 0 ; j < n - 1 ; j++){
        if(arr[j][0] > arr[j + 1][0])
            swap(arr[j],arr[j + 1]);
    }
}