Reputation: 7663
Hey guys can you help me out with writing a comparison function that would be use in comparison sorting algorithm. This is the standard function, but the number 5 must be regarded as being the lowest and 0 the largest.
So if we have data like this the numbers
0, 1, 5, 2, 3, 0, 1, 5, 4, 632, 0, 7
would be sorted to
5, 5, 1, 1, 2, 3, 4, 7, 632, 0, 0, 0
Here is pseudocode; no specific language.
int mycompar(int a, int b)
{
if (a > b) return 1;
if (a < b) return -1;
if (a == b) return 0;
}
Upvotes: 2
Views: 79
Reputation: 6363
The following C code works:
int mycompar(int a, int b){
int MAX = 5, MIN = 0;
return ( a==MAX || b==MIN ? -1 : ( b==MAX || a==MIN ? 1 : a-b) );
}
Upvotes: 0
Reputation: 1169
int mycompar(int a, int b) {
if ( a == b ) return 0;
if ( a == 5 || b == 0 ) return -1;
if ( a == 0 || b == 5 ) return 1;
return ( a > b ) ? 1 : -1;
}
This code should work.
Upvotes: 4
Reputation: 7112
The following code should work:
int mycompar(int a, int b)
{
if (a==b) return 0;
if (a==0 || b==5) return 1;
if (a==5 || b==0) return -1;
if (a>b) return 1;
if (a<b) return -1;
}
0 will always be higher than any other number and rise to the top, and 5 will always be lower than any other number and sink to the bottom.
EDIT: Check first and foremost if the number is 5 or 0.
Upvotes: 2