New and improved code:
Code:
void swap (double **p, double **q); /* wissel de pointer waardes om */
double length (double v[], int dim); /* bepaal de lengtes van de vectoren */
int main (void)
{
static int dim, num;
int i, j;
double **w, *v;
scanf ("%d %d", &dim, &num); /* read N and M */
w = calloc (num, sizeof (double *)); /* allocate array of M pointers */
assert (w != NULL);
v = calloc (num, sizeof (double ));
assert (v != NULL);
for (i = 0; i < num; i++)
{
/* allocate space for N dimensional vector */
w[i] = calloc (dim, sizeof (double));
assert (w[i] != NULL);
/* read the vector */
for (j = 0; j < dim; j++)
{
scanf ("%le", &w[i][j]);
}
}
for (i = 0; i < num; i++){
v[i] = length(w[i], dim);
}
/* acces the lengths and swap length and w vector in order*/
for (i = 0; i < num - 1; ++i){
for (j = num - 1; j > i; --j){
if (v[j-1] > v[j])
{
swap(&w[j-1], &w[j]);
swap(&v[j-1], &v[j]);
}
}
}
for (i = 0; i < num; i++){
for(j = 0; j < dim; j++){
printf("%e ", w[i][j]);
}
printf("\n");
}
return 0;
}
void swap(double **p, double **q)
{
double *tmp;
tmp = *p;
*p = *q;
*q = tmp;
}
double length (double v[], int dim)
{
int i;
double wl = 0.0;
for (i = 0; i < dim; ++i)
{
wl += ((v[i]) * (v[i]));
}
wl = sqrt(wl);
return wl;
}
I tested the scanning, it works now, the printing is fine as well. Even the calculating of the vector length works. The problem is that the vector gets sorted, but kinda half baked. The problem has to be in the bubble sort or the swap, can anyone help???