Hi,
I have a selection of variables with random numbers generated and stored in ints. What i want to do is sort these into ascending order.
I'm not sure how to do this in c, and any help would be appreciated.
Many Thanks
Hi,
I have a selection of variables with random numbers generated and stored in ints. What i want to do is sort these into ascending order.
I'm not sure how to do this in c, and any help would be appreciated.
Many Thanks
http://en.wikipedia.org/wiki/Sorting_Algorithm has a good few algorithms showing you how to sort data
Thanks... could use a bit more help if possible!
I have 7 variables, which would you suggest to be the best?
Thanks
well im gonna assume that they are in an array n use bubble sorting (the easyest but most inefficient varient.. but for 7 values who cares? )
i appologise for any mistakes and bugs and all that junk, its getting late and im a little ill but hey, finding bugs is the greatest part. if you goto the wikipedia article and read up on bubble sorting you should be able to follow whats going on.Code:void sortarray(int* myarray) { bool foundsort = True; int tmpvalue; while (foundsort == True) { foundsort = False; for (int i = 0; i <= 6; i++) { if (myarray[i] <= myarray[i+1]) { foundsort = True; tmpvalue = myarray[i]; myarray[i] = myarray[i+1]; myarray[i+1] = tmpvalue; } } } }
but basically, it itterates through the array if int's, if myarray[i+1] is greater than myarray[i], it swaps the two values around.
it keeps doing this until no values get swapped around. thus the greatest value is at myarray[0] and the largest at myarray[6]
If you don't want to write your own sort function, you can use the qsort() function. Here's a complete example that does what you want:Code:#include <stdio.h> #include <stdlib.h> int array[] = {5, 4, 3, 2, 1, 6, 0}; int compare_ints(const void *a, const void *b) { const int *ia = (const int *) a; const int *ib = (const int *) b; return (*ia > *ib) - (*ia < *ib); } void print_array() { int i; printf(" [ "); for (i = 0; i < sizeof(array)/sizeof(int); i++) { printf("%d ", array[i]); } printf("]\n"); } int main() { printf("Initial array:\n"); print_array(); qsort(array, sizeof(array)/sizeof(int), sizeof(int), compare_ints); printf("After sorting:\n"); print_array(); return 0; }
Actully they were not in an array, but could be if this was the simpler way of doing it?
It's better to keep them in an array than to keep in different variables like x,y,z... It'll shorten your algorithm and it'll be easier to reach each one. As gord says, bubble sort might be the worst algorithm to sort, but it's the easiest to keep in mind.
Registered Linux User : #338237
_
"Bart, with $10,000, we'd be millionaires! We could buy all kinds of useful things like... love!"
Linux forums... helping students do their homework since 1998.
How is this homework... its just a stage in me learning C.
was a joke, my apologies.
/me bows and tips hat
Bookmarks