Qsort - Alternate Sort Order

I have a program that uses (and should continue to use) an old sort function that implements qsort. I also have to provide a sorting function with the corresponding data to sort the data both ascending (if the line contains even numbers) and descending (if the line contains odd numbers).

For this, the data must be changed, the sort function cannot be changed.

The code is written in C , but I don’t have the corresponding code snippet for this particular problem.

The real question is:

How to convert the data so that the result matches the desired result below?

I have the following data (or similar)

String 1
String 2
String 3
String 4
String 5
String 6

EDIT: char **, - int.

:

String 5
String 3
String 1
String 2
String 4
String 6

, 1:1. , , 1 0 , .

, , , :

String 01
String 12
String 03
String 14
String 05
String 16

( ).

String 1
String 3
String 5
String 2
String 4
String 6
+3
4

, :

Struct DataValue
{
   string data;
   int value;
} 

{"01", 1} , , : , , . ( ) ( ), :

    int j = 0;
    for (int i = a.Count - 1; i >= 0; i -= 2) // fill bottom of list
    {
        b[a.Count - 1 - j] = a[i];
        j++;
    }

    j = 0;
    for (int i = a.Count - 2; i >= 0; i -= 2)  // fill root of list
    {
        b[j] = a[i];
        j++;
    }

, .

#, c. :

  List<int> a = new List<int>{1,2,3,4,5,6,7};

   b==> 6,4,2,1,3,5,7

and for:
  List<int> a = new List<int>{1,2,3,4,5,6};
  b==> 5,3,1,2,4,6
+3

(.. ), . , . , , . .

qsort.

int Comparer(void * v1, void * v2)
{
    char *s1 = (char *)v1;
    char *s2 = (char *)v2;

    // Here, extract the numbers from the ends of the strings.
    int n1 = // extract number
    int n2 = // extract number

    // First comparison sorts odd numbers above even numbers
    if ((n1 % 2) == 1)
    {
        // first number is odd
        if ((n2 % 2) == 1)
        {
            // second number is odd, so sort the numbers ascending
            return (n1 - n2);
        }
        else
        {
            // second number is even, which is "greater than" any odd number
            return -1;
        }
    }
    else
    {
        // first number is even
        if ((n2 % 2) == 0)
        {
            // second number is even, so sort the numbers descending
            return (n2 - n1);
        }
        else
        {
            // second number is odd, which is "less than" any even number
            return 1;
        }
    }
}
+2

9-i, i . , 9.

+1
  • Preprocess: ( _evens_) ( _odds _)
  • _odds_ : _odds_ * * .
  • _evens_ : _evens_ * * .
+1
source

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


All Articles