Javatpoint Logo
Javatpoint Logo

15. C program to sort the elements of an array in descending order

In this program, we need to sort the given array in descending order such that elements will be arranged from largest to smallest. This can be achieved through two loops. Outer loop will select an element and inner loop allow us to compare selected element with rest of the elements.

Original array:

C program to sort the elements of an array in descending order

Array after sorting:

C program to sort the elements of an array in descending order

Elements will be sort in such a way that largest element will appear on extreme left which in this case is 8. Smallest element will appear on extreme right which in this case is 1.

ALGORITHM:

  • STEP 1: START
  • STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.
  • STEP 3: SET temp =0
  • STEP 4: length= sizeof(arr)/sizeof(arr[0])
  • STEP 5: PRINT "Elements of Original Array"
  • STEP 6: SET i=0. REPEAT STEP 7 and STEP 8 UNTIL i<length
  • STEP 7: PRINT arr[i]
  • STEP 8: i=i+1.
  • STEP 9: SET i=0. REPEAT STEP 10 to STEP 13 UNTIL i<n
  • STEP 10: SET j=i+1. REPEAT STEP 11 and STEP 12 UNTIL j<length
  • STEP 11: if(arr[i]               temp = arr[i]
                  arr[i]=arr[j]
                  arr[j]=temp
  • STEP 12: j=j+1.
  • STEP 13: i=i+1.
  • STEP 14: PRINT new line
  • STEP 15: PRINT "Elements of array sorted in ascending order"
  • STEP 16: SET i=0. REPEAT STEP 17 and STEP 18 UNTIL i<length
  • STEP 17: PRINT arr[i]
  • STEP 18: i=i+1.
  • STEP 19: RETURN 0.
  • STEP 20: END.

PROGRAM:

Output:

Elements of original array:
5 2 8 7 1
Elements of array sorted in descending order:
8 7 5 2 1    
Next TopicC Programs





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA