问题
I am working on a project that sorts arrays inside the pointer arrays in a few different ways, though I am stuck on one way of sorting. The arrays are built in a way that the first number indicates the amount of numbers after it. For example, (3,0,23,1): this array has 3 numbers after the first index). I want to sort the array from lowest to highest number but I don't want to change the first index meaning the array will look like this (3,0,1,23). These are the arrays and the pointer array:
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[SIZE] = { arr1, arr2, arr3, arr4, arr5 };
This code is for the sorting function
for (i = 0; i < SIZE; i++)
{
for (j = 1; j < pArr[i][0]+1; j++)
{
if (pArr[i][j] < pArr[i][j - 1])
{
temp = pArr[i][j];
pArr[i][j] = pArr[i][j - 1];
pArr[i][j - 1] = temp;
}
}
}
I would like to use bubble sort or selection sort only as I am new to programming and don't know too much about the other sorting methods.
回答1:
Here you are.
#include <stdio.h>
void bubble_sort( int a[], size_t n )
{
for ( size_t last = n; !( n < 2 ); n = last )
{
for ( size_t i = last = 1; i < n; i++ )
{
if ( a[i] < a[i-1] )
{
int tmp = a[i];
a[i] = a[i-1];
a[i-1] = tmp;
last = i;
}
}
}
}
void sort_multiple_arrays( int * a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
bubble_sort( a[i] + 1, a[i][0] );
}
}
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 );
sort_multiple_arrays( parr, N );
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/43291939/how-can-i-sort-arrays-in-a-pointer-array-in-a-descending-order-using-bubble-sort