0
I’m having difficulty sorting in ascending order the values present in a vector using pointers, I tested and the problem is that it just shows the vector with the inverse typed sequence, and not in ascending order, follows the code for analysis:
int main(void){
int vec[5] = {},aux; // Vetor e aux pra ordernar
int *p; // ponteiro para o vetor
for(int i=0;i<5;i++){ // obter o vetor do usuario
printf("Digite o elemento de numero %d do vetor: ", i+1);
scanf_s("%d",&vec[i]);
}
p = &vec[0]; // Ponteiro no primeiro elemento do vetor
for (int i=0;i<5;i++) // loop de scaneamento do vetor
{
for (int j=0;j<5;j++)
{
if ((p+i)>(p+j)) // Ordena o vetor atravez dos ponteiros
{
aux = *(p+i);
*(p+i) = *(p+j);
*(p+j) = aux;
}
}
}
printf("\n\nSeu vetor ordenado: ["); // print do vetor ordenado
for(int i=0;i<5;i++){
printf(" %d ",vec[i]);
}
printf("]");
return 0;
}
Could someone help me to get it in ascending order, using the pointers to navigate the vector? Thank you.
Should you not compare the content of the addresses and not the addresses themselves?
– anonimo
I’m starting now with pointers,so I’m not familiar with this,could you explain me a little? where should I compare and how
– Exotic 011
Here
if ((p+i)>(p+j))
you are comparing two addresses and not two integers.– anonimo
I’m comparing two pointers, which are the requests by the statement in question ''pointers to navigate the vector',the problem would be,they are then receiving the values but will not make the shape increasing,?
– Exotic 011
But do you want to sort the addresses or values contained in these addresses? It doesn’t make much sense to sort the pointers since it doesn’t matter the value of these pointers but the values they point to.
– anonimo
I have to sort the values inserted in the vectors,
– Exotic 011
Write a program that reads 5 integers and store them in one vector. From there, , using pointers to navigate the vector, the values stored in the vector must , ordered from the smallest to the largest. The ordered vector must be displayed on the screen.
– Exotic 011
Exchange your code snippet for:
for (int i=0;i<4;i++) { for (int j=i+1;j<5;j++) { if (*(p+i) > *(p+j)) { aux = *(p+i); *(p+i) = *(p+j); *(p+j) = aux; } } }
– anonimo