Ok, so I have this program that sorts n number of integers in an array. If the integer is below Threshold it sorts them in ascending order and if the integer is equal to or larger than Threshold they are sorted in descending order.
I'm using the qsort function to do this, first to sort all of the integers in ascending order and then afterwards sorting them again with the threshold taken into account.
Now the actual question is, how come that if I call srand before filling my array with 'random' numbers its sorted in the way I want it, but if I don't, I just get some random sort.
PS: Obviously this is just an example code, but it displays what it is that I'm trying to do, and I don't know why this is working the way it is/isn't... and I'm somewhat new at programming in C.
Code:
#include <stdio.h>
#include <stdlib.h>
#define THRESHOLD 10
int CompareIntsAsc(const void* a, const void* b)
{
int* val1 = (int*) a;
int* val2 = (int*) b;
if( *val1 < *val2 )
{
return -1;
}
else if ( *val1 == *val2 )
{
return 0;
}
else
{
return 1;
}
}
int CompareIntsThreshold(const void* a, const void* b)
{
int* val1 = (int*) a;
int* val2 = (int*) b;
if( *val1 < THRESHOLD )
{
if( *val1 < *val2 )
{
return -1;
}
else if ( *val1 == *val2 )
{
return 0;
}
else
{
return 1;
}
}
else
{
if( *val1 < *val2 )
{
return 1;
}
else if ( *val1 == *val2 )
{
return 0;
}
else
{
return -1;
}
}
}
int main()
{
int Size = 20, Data[Size], i = 0;
int Range = Size;
srand(12);
for( i = 0; i < Size; i++ )
{
Data[i] = rand() % Range;
}
qsort(Data,Size,sizeof(int),CompareIntsAsc);
qsort(Data,Size,sizeof(int),CompareIntsThreshold);
for( i = 0; i < Size; i++ )
{
printf("%i\n",Data[i]);
}
getchar();
}