📜 ⬆️ ⬇️

Sort data and return them to the previous order

Quite often in sports programming or just the implementation of algorithms, it is necessary to sort the array of input data according to a certain criterion. While the response requires the original order. In this article I will look at several ways to make this minimal blood in C ++. If this topic is interesting or there are interesting suggestions, please…


Image By: Tobias Rad , Creative Commons Attribution-Share Alike 3.0 Unported License

The first idea was to sort the array with its algorithm, to remember all the pairs of exchanges of values ​​in the array, with whom they were swapped. And when it is necessary to return the original order, repeat the same exchanges in the reverse order. Of course, its sorting algorithm, written in a couple of minutes, does not even remotely catch up with std :: sort (). Therefore, there is a second idea, to memorize the initial indexes of records and sort by them using std :: sort ().
')
In the above methods, when filling an array with data, the Domino :: index field must be filled with the index number of the record.

The first method, using a static member and a functor:


The source code can be found here: http://codepad.org/0PWSzTBc

The second way, using a static member and operator <:


The source code can be found here: http://codepad.org/1zsTnk4s

The third way, using lambda (C ++ 0x):


The source code can be found here: http://codepad.org/5WRgCxLw

The first two methods are very similar, with the exception of the operator, which is transmitted explicitly or used by default by the sort function. The third method simply shows how much easier it is possible to get the same result, describing the operator right at the place of its use. Unfortunately, not all platforms for competitions in sports programming support C ++ 0x.

Source: https://habr.com/ru/post/121283/


All Articles