C Program to Sort the Elements of an Array in Descending Order (original) (raw)

Last Updated : 20 Nov, 2024

Sort an array in descending order means arranging the elements in such a way that the largest element at first place, second largest at second place and so on. In this article, we will learn different ways to sort an array in descending order in C.

The simplest method to sort the array in descending order is by using the in-built library function qsort(). Let's take a look at an example:

C `

#include <stdio.h> #include <stdlib.h>

// Comparator function to sort in descending order int comp(const void a, const void b) { return ((int)b - (int)a); }

int main() { int arr[] = {1, 3, 5, 4, 2}; int n = sizeof(arr) / sizeof(arr[0]);

// Sorting the array using qsort
qsort(arr, n, sizeof(int), comp);

for (int i = 0; i < n; i++)
    printf("%d ", arr[i]);
return 0;

}

`

qsort() function uses quicksort algorithm and needs a comparator function for guiding it to sort the array in descending order.

C language only provides the built-in implementation of quick sort algorithm. If you want to use other sorting algorithm apart from quicksort, you have to manually implement it as shown:

Table of Content

Using Selection Sort

Selection sort is a simple sorting algorithm that repeatedly finds the maximum element from the unsorted part of the array and places it at its position in the sorted part of the array until the complete array is sorted.

C `

#include <stdio.h>

// Selection sort implementation void sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int max = i; for (int j = i + 1; j < n; j++) { if (arr[j] > arr[max]) max = j; } if (max != i) { int temp = arr[max]; arr[max] = arr[i]; arr[i] = temp; } } }

int main() { int arr[] = {1, 3, 5, 4, 2}; int n = sizeof(arr) / sizeof(arr[0]);

// Calling selection sort on arr
sort(arr, n);

for (int i = 0; i < n; i++)
    printf("%d ", arr[i]);
return 0;

}

`

Using Bubble Sort

In Bubble Sort Algorithm, we repeatedly swap adjacent elements if they are in the wrong order. This process is repeated until the array is sorted in descending order.

C `

#include <stdio.h>

// Bubble sort implementation void sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] < arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }

int main() { int arr[] = {1, 3, 5, 4, 2}; int n = sizeof(arr) / sizeof(arr[0]);

// Perform bubble sort
sort(arr, n);

for (int i = 0; i < n; i++)
    printf("%d ", arr[i]);
return 0;

}

`

Similar Reads