C Program To Sort The Elements Of An Array In Descending Order
Arranging data in a specific sequence is a fundamental operation in computer science. Sorting an array in descending order means ordering its elements from the largest value to the smallest. In this article, you will learn how to implement a C program to sort the elements of an array in descending order.
Problem Statement
The challenge is to take an unsorted array of integers and rearrange them such that the largest element appears first, followed by the next largest, and so on, until the smallest element is at the end. This is a common requirement in data processing, analytics, and competitive programming.Example
Consider an array with the following elements:[5, 2, 8, 1, 9].
After sorting in descending order, the array should become: [9, 8, 5, 2, 1].
Background & Knowledge Prerequisites
To understand this article and the provided C program, you should have a basic understanding of:- C Programming Basics: Fundamental syntax, data types, and variable declarations.
- Arrays: How to declare, initialize, and access elements of an array.
- Loops:
forloops for iteration over array elements. - Conditional Statements:
ifstatements for comparing values. - Functions: Basic
mainfunction structure.
Use Cases
Sorting arrays in descending order is useful in various real-world scenarios:- Leaderboards: Displaying game scores or competition results from highest to lowest.
- Top N Items: Identifying the best-selling products, most visited websites, or highest-rated movies.
- Prioritization Queues: Processing tasks based on their importance or urgency, from highest to lowest priority.
- Financial Analysis: Ranking stocks by market capitalization or companies by revenue in decreasing order.
- Data Visualization: Preparing data for charts where larger values need to stand out first.
Solution Approaches
Approach 1: Bubble Sort for Descending Order
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. For descending order, elements are swapped if the first element is smaller than the second.
One-line summary: This approach repeatedly compares adjacent elements and swaps them to gradually "bubble" larger elements towards the beginning of the array.
// Sort Array in Descending Order (Bubble Sort)
#include <stdio.h>
int main() {
// Step 1: Declare and initialize an array
int arr[] = {5, 2, 8, 1, 9, 3};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements
int i, j, temp;
printf("Original array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
// Step 2: Implement Bubble Sort for descending order
// Outer loop for passes
for (i = 0; i < n - 1; i++) {
// Inner loop for comparisons and swaps
for (j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
// If the current element is smaller than the next, swap them
if (arr[j] < arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Step 3: Print the sorted array
printf("Sorted array in descending order: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
return 0;
}
Sample Output:
Original array: 5 2 8 1 9 3
Sorted array in descending order: 9 8 5 3 2 1
Stepwise Explanation:
- Initialization:
- An integer array
arris declared and initialized with some sample values.
- An integer array
n calculates the total number of elements in the array using sizeof.i, j, and temp are declared as integer variables for loop counters and temporary storage during swaps.- Print Original Array: A
forloop iterates through the array and prints its initial unsorted state. - Outer Loop (
for (i = 0; i < n - 1; i++)):- This loop controls the number of passes through the array. For an array of
nelements,n-1passes are sufficient.
- This loop controls the number of passes through the array. For an array of
- Inner Loop (
for (j = 0; j < n - i - 1; j++)):- This loop compares adjacent elements. The
n - i - 1part ensures that in each successive pass, the loop runs one element less, as the largest elements are already moved to the front (or the smallest elements to the end if ascending).
- This loop compares adjacent elements. The
arr[j] is compared with arr[j+1].- Comparison and Swap (
if (arr[j] < arr[j+1])):- If
arr[j](the current element) is smaller thanarr[j+1](the next element), they are in the wrong order for descending sort.
- If
temp is used to swap their values:temp stores arr[j].arr[j] gets the value of arr[j+1].arr[j+1] gets the value from temp.- Print Sorted Array: After the loops complete, the array
arrwill be sorted in descending order, and anotherforloop prints the final sorted array.