Code:
int comp(const void* a, const void* b)
{
int num1=**((int**)(a)), num2=**((int**)(b));
return num1<num2 ? -1 : num1==num2 ? 0 : 1 ;
}
int comp_rev(const void* a, const void* b)
{
return -comp(a, b);
}
You could try using something like that with the qsort() function. You just need to assign the arrays of integer pointers first for the ascending and descending.
Code:
int *ascSort[SIZE];
int *descSort[SIZE];
for(i=0;i<SIZE; i++)
{
ascSort[i]=&inputAry[i];
descSort[i]=&inputAry[i];
}
qsort(ascSort, SIZE, sizeof(int*), comp);
qsort(descSort, SIZE, sizeof(int*), comp_rev);
This method neither changes the original array or creates additional integer arrays.
Code:
Please enter 5 integers to be sorted:
5
8
3
1
2
Ascending order:
1, 2, 3, 5, 8,
Descending order:
8, 5, 3, 2, 1,
Original order:
5, 8, 3, 1, 2,
Edit:
The way it works is that it passes the data and the comparison functions to the qsort() function, which does all the heavy lifting for you. qsort() is part of the C standard library.
Here is its prototype:
void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );
The void * base argument just means that you can pass a pointer to any kind of array there. The function uses size_t num (the number of elements in the array) and size_t size (the size of each individual element) to tell how it can move around in base. Void pointers can be pointers to anything; you just need to recast them as pointers to other types to dereference them as those.
The last argument to qsort() is a function pointer that gives qsort a way to determine what's higher or lower in the array. You can use function pointers more or less like regular pointers. One way to think about how function pointers work is that, instead of pointing to data memory, function pointers point to instruction memory.
int ( * comparator ) ( const void *, const void * ) just means that the function the function pointer comparator points to has to return an int and take two const void pointers as arguments.
For qsort() to work as expected, whatever function comparator points to must return a negative number if the first number is smaller than the second, 0 if the two numbers are equal, and a positive number if the first number is larger than the second. If you negate whatever that function returns ( like in comp_rev() ), qsort will give you the reverse of the order it would have normally.
It is important to note that qsort() rearranges the elements of base, which in our case are just pointers to the elements of the original array - the original array is left untouched.