It is requested to create a vector P that contains the position of the elements of A, so that the list is traversed in order from smallest to largest. List A of M naturals.
When generating the vector P it shows me numbers that are not the ones I want. I don't know if it would be showing me the memory address.
I first tried to do it with the for loop but changed it thinking that's what was wrong. I also tried to use pos as pointer but can't fix it.
typedef int T_vector[101];
void cargar_vector(T_vector, short *);
void generar_p(T_vector, short, T_vector);
void mostrar_vector(T_vector, short);
int main()
{
T_vector A, P;
short M;
cargar_vector(A, &M);
generar_p(A, M, P);
mostrar_vector(A, M);
mostrar_vector(P, M);
return 0;
}
void cargar_vector(T_vector A, short *M)
{
int i;
printf("Ingrese el tamaño del vector: ");
scanf("%hd", M);
for (i = 1; i <= *M; i++)
{
printf("Ingrese el elemento %d: ", i);
scanf("%d", &A[i]);
}
}
void generar_p(T_vector A, short M, T_vector P)
{ /*fijar con recorrer vector*/
int men, i, j, l, k;
short pos;
men = A[1];
j = 1;
for (i = 2; i <= M; i++)
{
if (A[i] < men)
{
men = A[i];
pos = i;
}
}
P[j] = pos;
j++;
l = 1;
k = M;
for (i = 1; i <= M; i++)
{
if (A[i] >= men && i != pos)
{
while (A[i] < A[l] && A[i] < A[k])
{
P[j] = i;
j++;
l++;
k--;
}
}
}
}
void mostrar_vector(T_vector P, short M)
{
int j;
printf("El vector es :");
for (j = 1; j <= M; j++)
{
printf("%d|", P[j]);
}
}
Let's start with
cargar_vector
:M
. That should be an output parameterA
Applying the changes:
Let's go with
generar_p
.It would be easier if you initialize
P
with an incremental sequence. Thus, the elementP[n]
would point to the elementA[n]
.Once this is done, you can easily program the bubble algorithm so that it moves the indexes
P
according to the ordering that they are asking for:If you now want to display the vector
A
ordered according to the sequence given byP
, you need a new function:I'm answering this question just to dust off my C, and for that I took @eferion's accepted answer and:
First I created two files at the main level. One called t_vector.c (with all the acquisition and ordering functions), and another t_vector.h (with the data types of each function in t_vector.c ).
t_vector.h :
t_vector.c :
I then had them called in the main function vector.c :
With this, the main function is "clean" and clear.
Running gives us:
I just did it to relearn my C, and to share my "relearn".