Home > Blockchain >  Sort 2d C array by first element in subarray
Sort 2d C array by first element in subarray

Time:07-02

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}}

?

CodePudding user response:

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]);
    }
}

CodePudding user response:

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
  • Related