How to sort the IP addresses of the four fields?
Analysis:
Sorting is based on the integer of each field, and the entire IP address is a string type. Therefore, you need to read fields one by one.
Note that each field is 0 ~ 255, which can be expressed in one byte. To compare the size, the unsigned char type is used.
After reading, the most natural idea is to compare fields one by one and compare four fields in sequence, which can be called separately for sorting each field.
Considering the principle of base sorting, you may wish to use 256 as the base to implement base sorting.
Think of this, since there is such a special number 256, our fields are all the remainder of the modulo 256, We can multiply all the fields by the corresponding power of 256 according to their location; in this way, we get an integer, you only need to sort the integer. This is the same as the operating principle, that is, 256 hexadecimal. Therefore, if the operating system compares the size of the result, the result is sorted by a query. However, this method must correspond to the two by pointer or subscript.
Think of this, rememberC LanguageThe Union mechanism is provided. Definition
Union
{
Unsigned char one_ip [4];
Unsigned long four_ip;
} IP;
In this way, you can read four sub-segments with IP. one_ip and compare them with IP. four_ip. This is similar to the above, but this step is missing. It is quite concise. However, you must pay attention to the order of the fields to be read. The high field must be at the High Level. Otherwise, the comparison result is meaningless.