Ciao Simone,
eccoti un esempio:
codice:
#include <stdio.h>
#include <malloc.h>
#define RIGHE 3
#define COLONNE 4
void BubbleSort(int *Mat, int nConta)
{
register int a, b;
register int t;
for ( a = 1; a < nConta; ++a )
{
for ( b = nConta - 1; b >= a; --b )
{
if ( Mat[b-1] > Mat[b] )
{
t = Mat[b-1];
Mat[b-1] = Mat[b];
Mat[b] = t;
}
}
}
}
int main(int argc, char* argv[])
{
int nTot = RIGHE * COLONNE;
int r, c;
int matrice[RIGHE][COLONNE] = {{9,8,4,5} ,{7,6,10,1}, {3,2,7,8}};
printf("matrice non ordinata:\n");
for (r = 0; r < RIGHE; r++ )
for (c = 0; c < COLONNE; c++)
printf("%d ", matrice[r][c]);
printf("\n\n");
BubbleSort((int*)matrice, nTot);
printf("matrice ordinata:\n");
for (r = 0; r < RIGHE; r++ )
for (c = 0; c < COLONNE; c++)
printf("%d ", matrice[r][c]);
printf("\n\n");
return 0;
}
Per ordinare la matrice utilizziamo l'algoritmo 'Bubble Sort' che, nel caso in cui i dati da ordinare siano pochi, è più efficiente perfino del QuickSort.
Praticamente si procede per confronti successivi. Se l'elemento precedente è maggiore del successivo, i due elementi vengono scambiati:
codice:
if ( Mat[b-1] > Mat[b] )
{
t = Mat[b-1];
Mat[b-1] = Mat[b];
Mat[b] = t;
}
Alla fine, l'array risulta ordinato.