Arranging Array elements in ascending order

150 views
Skip to first unread message

Goktug Erol

unread,
Oct 20, 2021, 8:58:01 AM10/20/21
to C++ GCU Forum
Can someone help me to arrange array elements in ascending order?

It should be;

The elements are= 0s,1s,2s

1s > 0s but <2s
2 > 1s, 0s
0s <1s, 2s

///

This is what I did (if is there a mistake pls help me to fix it. 

Screenshot 2021-10-20 15.55.30.png

William Fynn

unread,
Oct 20, 2021, 6:42:10 PM10/20/21
to C++ GCU Forum
We may try out a brute force approach first and then try and make it better.
A nested for loop may help in this case. Within each iteration, we check and swap when the next element is less than the current element.

for (auto i = std::begin(arr); i < std::end(arr); ++i)
    {
        for (auto i = std::begin(arr); i < std::end(arr) - 1; ++i)
        {
            if (*(i + 1) < *i)
            {
                std::iter_swap(i, i + 1);
            }
        }
    }

I hope this helps...

William Fynn

unread,
Oct 20, 2021, 7:10:24 PM10/20/21
to C++ GCU Forum
We can improve on the approach above, using std::map which holds data in ascending order.
  
    Creating a std::map object to help record some values.
        std::map<int, int> all_values;

    Since we do not know the size of the array, we can call the range-based for loop to iterate the array
    and insert each element of the array into the map object, incrementing the count on each iteration.
        for (int elem : arr)
        {
            ++all_values[elem];
        }

    We will iterate over the elements in the map and insert into our array as many times as there may be in the second value of each pair.
    keeping track of the current index in the array.
        int index {-1};
        for (auto& [num, count] : all_values)
        {
            for (int i{}; i < count; ++i)
            {
                arr[++index] = num;
            }
        }
  
    Currently, our array holds all elements in ascending order.
Reply all
Reply to author
Forward
0 new messages