ordering algorithm

I'm writing an ordering algorithm for a defined 10-elements array but it doesn't work. The array is always the same.

 ``1234567891011121314151617181920212223242526272829303132`` ``````#include int v[10]={5,4,2,6,8,9,1,0,3,7},i; //Funzione per lo scambio void swap(int *a,int *b){ int *tmp; tmp=a; a=b; b=tmp; } //Algoritmo int algo(int *v){ int max, n=10; for(i=0; i<10; i++){ if(v[i]>v[i+1]){ max=v[i]; } swap(&v[max], &v[n-1]); n--; } } //Corpo del programma int main(){ algo(v); printf("Vettore ordinato:%d",v[0]); for(i=1; i<10; i++){ printf(",%d",v[i]); } }``````
Your swap function does nothing. You are swapping (local) pointers. YOu need to swap values instead.
The first thing I notice is that your swap function does not work.

you change the value of the non-dereferenced pointer, not the dereferenced one.

try it like this
 ``123456`` ``````void swap(int *a,int *b){ int tmp; tmp = *a; *a = *b; *b = tmp; }``````

... or in C++03 with references
 ``123456`` ``````void swap(int& a,int& b){ int tmp; tmp = a; a = b; b = tmp; }``````

... and with templates
 ``1234567`` ``````template void swap(T& a, T& b){ T tmp; tmp = a; a = b; b = tmp; }``````

... and using the copy constructor
 ``123456`` ``````template void swap(T& a, T& b){ T tmp = a; // copy construction a = b; b = tmp; }``````

... and in C++11 with move
 ``123456`` ``````template void swap(T& a, T& b){ T tmp = std::move(a); a = std::move(b); b = std::move(tmp); }``````

The last version is basically the std::swap function
You can go with any of those, use one you understand or learn how the others work, it's up to you :)
Last edited on