问题
If I have 5 arrays and one array of pointers that contains all of the 5 arrays, and I need to write a function that will sort every single one of the arrays using the pointers array only, how can I do that?
The function needs to sort every single one of the array starting from the index 1 (!) and not 0.
int arr1[] = { 3, 9, 6, 7 };
int arr2[] = { 2, 5, 5 };
int arr3[] = { 0 };
int arr4[] = { 1, 6 };
int arr5[] = { 4, 5, 6, 2, 1 };
int * parr[] = { arr1, arr2, arr3, arr4, arr5 };
I know how to sort one array but I got a bit lost when I tried to sort every single one of the arrays using the pointers array in the most efficient way possible. Maybe there's an option to sort every array but in one loop? Because it seems a bit weird to do a whole "for" loop for every single one of the arrays
NOTE the first element of each array indicates the size of each one. For example : in arr1[0]
is 3 so the amount of numbers that will come after the index 0 in that array is 3 (9,6,7).
回答1:
You can call in a loop standard C function qsort
for each element of the array parr
.
For example
#include <stdio.h>
#include <stdlib.h>
int cmp( const void *a, const void *b )
{
return ( *( const int * )b < *( const int * )a ) -
( *( const int * )a < *( const int * )b );
}
int main(void)
{
int arr1[] = { 3, 9, 6, 7 };
int arr2[] = { 2, 5, 5 };
int arr3[] = { 0 };
int arr4[] = { 1, 6 };
int arr5[] = { 4, 5, 6, 2, 1 };
int * parr[] = { arr1, arr2, arr3, arr4, arr5 };
const size_t N = sizeof( parr ) / sizeof( *parr );
for ( size_t i = 0; i < N; i++ )
{
qsort( parr[i] + 1, parr[i][0], sizeof( int ), cmp );
}
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < parr[i][0] + 1; j++ )
{
printf( "%d ", parr[i][j] );
}
putchar( '\n' );
}
return 0;
}
The program output is
3 6 7 9
2 5 5
0
1 6
4 1 2 5 6
来源:https://stackoverflow.com/questions/43191792/sorting-5-arrays-in-one-function