Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
June 18th, 2013, 12:27 AM
 lolo07
Registered User

Join Date: Jun 2013
Posts: 1
Time spent in forums: 1 h 10 m
Reputation Power: 0
Sort random arrays with a float range

I'm having trouble setting up the following assignment:

Write a C program that sort an array of 1000 elements. The array contains random
float numbers between 0.5 and 19.5

The user will have the option to choose between:
1. Incremented sort (lowest value to highest).
2. Decremented sort (highest value to lowest).

Requirements:
Implement user defined functions to execute the sorting process.
The function prototypes are as follows:

1. void incrementArraySort(float A[], int size)
2. void decrementArraySort(float A[], int size)

Where A is the array to be sorted, the variable size denote the size of array A.
Note the functions return type is void.
• Display the result in the command line.

so far I have this (I know is wrong but is what I could came out with )( I got to set up 0.5 as the min number, but how do I set 19.5 as the max number?):

Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void incrementArraySort(float A[], int size);
void decrementArraySort(float A[], int size);

int main ()
{
int i;
float A[1000];
for ( i = 0; i <= 999; i++)
{
A[i] = (float)i + 0.5;

}
srand((unsigned) time( NULL ) );
for ( i = 0; i <= 999; i++)
{
int index1 = i;
int index2 = rand()%1000;

int temp;
temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
}
for ( i = 0; i <= 999; i++)
printf("element[%d]: %f", i, A[i]);

return 0;
}

#2
June 20th, 2013, 02:21 AM
 Homi@th
Contributing User

Join Date: Jun 2013
Posts: 40
Time spent in forums: 1 Day 8 h 58 m 5 sec
Reputation Power: 18
1. To make random float between in range a and b you can use this.

Quote:
 (b-a) * ((float)rand() / RAND_MAX) + a

Code:
srand(time( NULL ) );

for (int i =0;  i<1000; i++)
A[i] = (19.5 - 0.5)  * ((float)rand() / RAND_MAX) + 0.5;

2. Using qsort from stdlib is a quick way to sort.

Ascending sort:
qsort(A, 1000, sizeof(float), asc_compare);

Decending sort:
qsort(A, 1000, sizeof(float), desc_compare);

Comparing floating points is not easy, but there is some trick. We compare bit pattern as integer and can tell which is larger or smaller.

Code:
int asc_compare(const void * a, const void * b){
return ( *(int*)a  < *(int*)b );
}

int desc_compare(const void * a, const void * b){
return ( *(int*)a  > *(int*)b );
}

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Sort random arrays with a float range