Example:
If the elements of array are: 20, 2, 10, 6, 52, 31, 0, 45, 79, 40
Array sorted in descending order: 79, 52, 45, 40, 31, 20, 10, 6, 2, 0
Required knowledge:
Basic C programming, If else, For loop, ArrayAlgorithm:
Here we will use basic algorithm to sort arrays in descending order:Step 1: Read elements in array.
Step 2: Set i=0
Step 3: Set j=i+1
Step 4: If array[i] < array[j] then swap value of array[i] and array[j].
Step 5: Set j=j+1
Step 6: Repeat Step 4-5 till j<n (Where n is the size of the array)
Step 7: Set i=i+1
Step 8: Repeat Step 3-7 till i<n
Program:
/**
* C program to sort elements of array in descending order
*/
#include <stdio.h>
int main()
{
int arr[100];
int size, i, j, temp;
/*
* Read size of array and elements in array
*/
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/*
* Array sorting code
*/
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
/*
* If there is a smaller element towards left of the array then swap it.
*/
if(arr[i] < arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
/*
* Prints the sorted array
*/
printf("\nElements of array in sorted descending order: ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}
Output
Enter size of array: 10
Enter elements in array: 20 2 10 6 52 31 0 45 79 40
Elements of array in sorted descending order: 79 52 45 40 31 20 10 6 2 0
Enter elements in array: 20 2 10 6 52 31 0 45 79 40
Elements of array in sorted descending order: 79 52 45 40 31 20 10 6 2 0
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to sort elements of array in ascending order.
- C program to sort even and odd elements of array separately.
- C program to put even and odd elements of array in two separate array.
- C program to search an element in an array.
- C program to find maximum and minimum elements in an array.
- C program to count total number of negative elements in an array.
- C program to count total number of duplicate elements in an array.
- C program to count frequency of each element in an array.
- C program to merge two array in single array.
- C program to find reverse of an array.
- C program to find upper triangular matrix.
- C program to find lower triangular matrix.
- C program to find transpose of a matrix.
- C program to find determinant of a matrix.