简体   繁体   中英

Swap two vectors in C

I have to write aa program where vectors are sorted from smallest to largest. I use a bubble function with swap to swap the two vectors. The swap and bubble code were given, but the problem is it doesn't swap the vectors. The assignment says to use this swap function and "call it" with the address of a vector.

void swap (double **p, double **q)
{
double *temp;

temp=*p;    
*p=*q;      
*q=temp; 
}





int main (void)
{
int dim, num;
int i, j;
double **w, a[100];
double size;

scanf ("%d %d", &dim, &num);          /* read N and M */
w = calloc (num, sizeof (double *));  /* allocate array of M pointers */
for (i = 0; i < num; i++)
{
    /* allocate space for N dimensional vector */
    w[i] = calloc (dim, sizeof (double));
    /* read the vector */
    for (j = 0; j < dim; j++)
    {
        scanf ("%le", &w[i][j]);
    }
}

/*Length*/
for(i=0; i<num; ++i)
{
    size=0.0;
    for(j=0; j<dim; ++j)
    {
        size+=pow(w[i][j],2);
    }
    a[i]=sqrt(size);
}

    i=0;
    for (j = num - 1; j > i; --j)
    {
        if (a[j-1] > a[j])
        {
            swap(&w[j-1], &w[j]);
        }
        i++;
    }
return 0; 
}

Turning my comment into an answer...

When you swap two items in w you also need to swap the two corresponding values in a so that the two arrays match each other.

if (a[j-1] > a[j])
{
    swap(&w[j-1], &w[j]);
    double temp = a[j-1];
    a[j-1] = a[j];
    a[j] = temp;
}

In addition, you should dynamically allocate a since the user could enter a value for num greater than 100.

double **w;
double * a;
double size;

scanf ("%d %d", &dim, &num);          /* read N and M */
w = calloc (num, sizeof (double *));  /* allocate array of M pointers */
a = calloc (num, sizeof (double));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM