• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

Trouble sorting this array.

redman223

Gawd
Joined
Oct 28, 2006
Messages
1,013
I want to sort this in ascending order

double x[]={2.5, 1.5, 4.0, 7.0, 3.5, 6.5, 8.5, 1.0};

I know I screwed it all up, but here is what I have so far:

Code:
#include <stdio.h>

int main(void)
		
{

	int k, j, m, npts=8;
	double hold;
	double x[]={2.5, 1.5, 4.0, 7.0, 3.5, 6.5, 8.5, 1.0};

	for (k=0; k<=npts-2; k++)
	
	{

		m = k;
		for (j=k+1; j<=npts-1; j++)
			if (x[j] < x[m])
				m = j;
		hold = x[m];
		x[m] = x[k];
		x[k] = hold;

	}

	return;

}

I guess what I was trying to do was set the first value of the array to the lowest number in the array and continue that process until they were all in order. But I messed up somewhere. Btw, I only know very basic C commands.
 
Really? Well that makes me feel better, lol.

But why doesn't it do anything for me? I am using visual studio (I am REALLY new to this stuff, but I have figured out how to write code, build it, and start without debugging) and when I run the program it just says press any key, and closes. I thought it would print out some values or something showing me that it correctly re-organized the array.....hmm there must be a printf statement needed right? But what would I ask it to print out?
 
Yes, you have to add in some code to print the values in the array.

You have familiarity with the for loop, so how would you apply that to printing out the values from the array?

Without setting any type of significant digit precision, this is what I get by compiling your code as is with a couple lines added to print out the array values.

Code:
llib@sakura:~$ ./a.out
1.000000 1.500000 2.500000 3.500000 4.000000 6.500000 7.000000 8.500000
 
I know that it would go right before the return value. But I have never printed out an array before. I tried:

printf(&x[]);

But it didn't work.
 
But....

printf("%f \n" ,x[k]);

almost worked....just a little more tweaking.

Next question. To arrange this all in Descending order, I will just have to change:

j=k+1 to j=k-1 right?
 
printf("x values: \n");
for (k=0; k<=npts-1; k++)
printf("%f \n" ,x[k]);

Worked perfect. Thanks again.
 
Back
Top