# Sorting Array Descending - need help!

Printable View

• 10-16-2006
mshazny
Sorting Array Descending - need help!
This this my coding, i want to convert it into Descending and output like :

How many marks do you have [1 to 20] ? : 4
Enter mark 1 : 50
Enter mark 2 : 55
Enter mark 3 : 45
Enter mark 4 : 60

The sorted array in ascending order:
45
50
55
60

The sorted array in descending order:
60
55
50
45

The incomplete coding are below, can sumone help me finish it..

Code:

```#include <stdio.h> #include <conio.h> #define k 20 int main() {   int a[k], n, p, j, i, small_j, smallest, biggest, big_j;   printf("\nHow many marks do you have [1 to 20] ? : ");   if(scanf("%d", &n) == 1 && n>0 && n<=k)  {         for(j=1; j<n+1; j++) {         printf("Enter mark %d :  ",j);         scanf("%d", &a[j]);         }         for(p=0; p<n; p++)         {                 smallest = a[p];                 small_j = p;                 for(j=p; j<n+1; j++)                         if(a[j] < smallest)                         {                                 smallest = a[j];                                 small_j = j;                         }                         a[small_j] = a[p];                         a[p] = smallest;         }         printf("\nThe sorted array in ascending order:\n");         for(j=0; j<n; j++) printf("%d\n", a[j]);         } return 0; }```
• 10-16-2006
SpaceCadet
You can sort an array using the qsort C-style algorithm.

The list container provides sort and splice capabilities if you want to take a more C++ oriented approach.
• 10-16-2006
indigo0086
if you must implement your own sorting algorithm and not just utilize a library, look up different types such as bubble, insertion, merge, quick sort algorithms.
• 10-16-2006
Salem
> for(j=1; j<n+1; j++)
Your sort and print function correctly start at index 0 in the array.

j = 0 ; j < n
is the best thing for looping over your array.
• 10-16-2006
robatino
You can also use C++'s sort() - a comparison between qsort() and sort() at

http://theory.stanford.edu/~amitp/rants/c++-vs-c/

Salem: One can optimize the loop some more by using "j != n" instead of "j < n", which works as long as j and n are integers. I've also tried starting at n and decrementing to 0, as in

Code:

```int j=n; while (j--) {   ... }```
which reduces the test to comparison with 0, although the difference, if any, is probably microscopic.

Edit: Sorry Salem, after reading your post more closely I saw you were concerned with the issue of getting the index right, not the efficiency (which shouldn't be an issue here).
Edit: Changed "j" to "j and n".
• 10-17-2006
iMalc
Two of your loops go one past the end and cause buffer overruns.
The loop that prints out the results at the end is correct.