-
Sorting an array
I have looked through the forums for a problem similar to mine but given the specifics of my particular assignment, none of the posts (that I've seen so far) have similar structures.
I have an array of a given length... in this case, we'll say:
input[5];
using a function named larger(a, b) in another.c file, which determines which of two ints is larger, how do I sort the elements of an array in ascending order? I've been sitting here for hours messing with it but I keep confusing myself.
This is what I have so far, which is way off, but just to show you the code structure for this part of the code.
Code:
for(j = total; j > 0; j--) /* total is the length of the array */
{
for(i = 0; i < j; i++)
{
temp = larger(input[i], input[j]);
if(temp = input[i])
{
temp1 = input[j];
input[j] = input[i];
input[i] = temp1;
}
}
}
Thank you in advance for taking time to look at this.
-
I posted a qsort program a few days ago, under the heading Golf Clubs, Cash. There may be something there to help you.
Rossco
-
Whilst I recommend going with qsort instead of rolling your own sorting algorithm, there are a few things you should learn with respect to the code you have written.
1. There is a buffer overrun. The first loop start with j equal to total, which is the length of the array, so item j does not exist. j would need to start at length-1.
2. Comparison uses ==, not =. This line would not do what you wanted:
Code:
if(temp = input[i])
3. a comparison function such as your 'larger' function only needs to return a BOOL indicating IF the first value is larger than the second. It doesn't actually need to return the value of which one is larger. You've probably written more of a 'max' function.