A
A
Anatoly Pleshkov2021-12-10 11:06:02
C++ / C#
Anatoly Pleshkov, 2021-12-10 11:06:02

How to sort the fractional and integer parts of a number in C++?

Help me please. It is necessary to solve a problem in C ++, given a stream of input data presented as rational numbers, you need to sort these numbers in non-decreasing order of the integer part, and in descending order of the fractional part. i.e. with input data: 2.3; 2; 2.4; 5.2; 5.1; 7.9; 6; . The answer should be 2.4; 2.3; 2; 5.2; 5.1; 6; 7.9;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-12-10
@Anatolii_9

The integer part can be obtained using floor(v)
The fractional part: (v - floor(v))
Use the standard sort to sort.
By the way, you can sort an array (you already have it in memory), when they talk about a stream, then this is something potentially infinite, you receive portions of data from the stream in parts and process them.
Accordingly, if you really have a thread, then you need to build a tree from its data. You can use the standard map for this. The data will fit into the tree as it arrives with simultaneous sorting. You can get a sorted list from a tree simply by traversing the tree using an iterator.
The data in the tree is sorted by key. For a key, you can use something like this: floor(v) + (1 - (v - floor(v)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question