+ 9
std::sort() has an overload that accepts a comparator function (a lambda will also do the trick). https://en.cppreference.com/w/cpp/algorithm/sort You can play around with the comparator function by changing its return value to get the desired output 👍
26th Aug 2022, 5:24 PM
Ipang
+ 5
Can you write your own sort function? Try it by using math.abs( v[i] ) , instead of v[i] , when comparing values... abs() returns numbers absolute value. Ex: abs(-5) => 5 , abs(5) => 5
26th Aug 2022, 5:11 PM
Jayakrishna 🇼🇳
+ 3
It's for calculating absolute value of a number. https://en.cppreference.com/w/cpp/numeric/math/abs
27th Aug 2022, 3:14 AM
Ipang
+ 3
i personally upvote the advice to use std::sort overloading because implementing sorting algorithms manually is a big pain & usually not that effective if you're not really into this topic
27th Aug 2022, 1:05 PM
Patrick
Patrick - avatar
+ 3
Mirielle I made a modification to your code. Used template for more flexibility and tweaked the lambda so that negative values are placed to the left when there are repeated absolute numbers. It adds an additional level of sorting, I think. https://code.sololearn.com/cLyQJ05Sgsh6/?ref=app
28th Aug 2022, 3:21 PM
Bob_Li
Bob_Li - avatar
+ 2
Manav Roy No. It yields positive value, but not change original. If you want to change, you can change by num = abs(num) ;
27th Aug 2022, 8:23 AM
Jayakrishna 🇼🇳
+ 2
Manav Roy it's a lambda expression. Think of it as an anonymous function.Here it is used to modify the behavior of sort(). https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=msvc-170
29th Aug 2022, 4:44 PM
Bob_Li
Bob_Li - avatar
+ 1
Mirielle The fact that we can code on the phone is amazing in itself. But yes, typing is a challenge. That's why my secret weapon is a Bluetooth external keyboard😅. Maybe someday we'll have AI enhanced ide, where we would just copy and paste the problem and the code would be auto generated... Tools like Kite and TabNine are available for quite some time already.
28th Aug 2022, 11:06 PM
Bob_Li
Bob_Li - avatar
+ 1
why you can't just code on a pc? or you don't have one
29th Aug 2022, 3:53 AM
Patrick
Patrick - avatar