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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<stdio.h>

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
1
2
3
4
5
6
void swap(int *a,int *b){
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}


... or in C++03 with references
1
2
3
4
5
6
void swap(int& a,int& b){
    int tmp;
    tmp = a;
    a = b; 
    b = tmp;
}


... and with templates
1
2
3
4
5
6
7
template <typename T>
void swap(T& a, T& b){
    T tmp;
    tmp = a;
    a = b;
    b = tmp;
}


... and using the copy constructor
1
2
3
4
5
6
template <typename T>
void swap(T& a, T& b){ 
    T tmp = a; // copy construction
    a = b;
    b = tmp;
}


... and in C++11 with move
1
2
3
4
5
6
template <typename T>
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
Registered users can post here. Sign in or register to post.