Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sorting numbers in arrays

Status
Not open for further replies.

houksyndrome

Technical User
Jun 27, 2001
7
US
I have another question. This one is about sorting numbers in an array. I want to write a program that will print out the largest number in an array. I have seen lots of threads about qsort but I'm confused as to how to use it. I have tried writing something like this.

#include <stdio.h>
#include <stdlib.h>

float data[10];

main()
{
data[0]=8.0;
data[1]=7.4;
data[2]=8.6;
data[3]=6.4;
data[4]=20.0;
data[5]=3.4;
data[6]=2.3;
data[7]=13.5;
data[8]=7.7;
data[9]=9.2;

qsort(data, 10, sizeof(float), )
/* I think I need a pointer to a function there, but I don't understand how to use those */

If anybody can help me with this I would be very gratefull. Thanks in advance.

Andrew

 
Hi

Here's what you need:

The comparing function declaration ...
int compare(const void *, const void *);

The call to qsort ...
qsort((void *)data, 10, sizeof(data[0]), compare);

The comparing function ...
int compare(const void *a, const void *b)
{
float x, y;
x = *(float *)a;
y = *(float *)b;
if(x == y) return 0;
else return (x<y)? -1: 1; /* stores in ascending order */
/* return (x>y)? -1: 1; stores in descending order */
}

But if you just want to print the largest why not...
[ignore]max = data[0];
for(i=0; i<10; i++)
max = (max<data)? data: max;
[/ignore]
Hope it helps.

Bye.
Ankan.

Now, could you please help me... Thread205-112554 Please do correct me if I am wrong. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top