Ciao Puntino,
Per la dimensione di un array, non puoi usare una variabile( è strano che non ti dia l'errore in compilazione. A me, il visual studio 2008, dà l'errore "expected constant expression"). Devi usare un valore costante:
codice:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ELEM 10
void bubblesort(int nelem, int *a);
void fast_bubblesort(int nelem, int *a);
int main()
{
//int nelem = 10;
int i = 0;
int a[MAX_ELEM];
int m = 0;
srand((int)time(NULL));
for(i; i < MAX_ELEM; i++)
{
a[i]= rand() % 100;
printf(" %d", a[i]);
}
printf("\n");
//bubblesort(MAX_ELEM, a);
fast_bubblesort(MAX_ELEM, a);
for(m = 0; m < MAX_ELEM; m++)
{
printf(" %d", a[m]);
}
printf("\n");
system("PAUSE");
return 0;
}
void bubblesort(int nelem, int *a)
{
register int i, j, temp;
for(i = 1; i < nelem; ++i)
{
for(j = nelem-1; j >= i; --j)
{
if( a[j-1] > a[j] )
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
}
void fast_bubblesort(int nelem, int *a)
{
register int i, j;
for(i = 1; i < nelem; ++i)
{
for(j = nelem-1; j >= i; --j)
{
if( a[j-1] > a[j] )
{
a[j-1] ^= a[j];
a[j] ^= a[j-1];
a[j-1] ^= a[j];
}
}
}
}
La seconda versione dell'algoritmo (funzione fast_bubblesort), è più veloce rispetto alla prima. Utilizza infatti l'operatore XOR del C e si evvita l'utilizzo di una variabile temporanea.