How can I sort the arrays in an array of pointers in descending order using bubble sorts or sort sort?

I am working on a project that sorts arrays within arrays of pointers in multiple ways, although I am stuck on one of the sorting methods. The arrays are constructed in such a way that the first number indicates the number 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 , which means the array will look like (3,0,1,23). These are arrays and an array of pointers:

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 sort 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 sort or sort for bubbles only , as I am new to programming and don't know too much about other sorting methods.

+1


source to share


1 answer


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;
}

      



Program output

3 6 7 9 
2 5 5 
0 
1 6 
4 1 2 5 6 

      

0


source







All Articles