C Program For Bubble Sort In Descending Order
Sorting data in a specific order is a fundamental operation in computer science. When you need to arrange elements from the largest to the smallest, a descending sort is essential.
In this article, you will learn how to implement the Bubble Sort algorithm in C to arrange an array of numbers in descending order, along with a clear code example and step-by-step explanation.
Problem Statement
The challenge is to efficiently arrange a given list or array of numerical data such that the largest element appears first, followed by progressively smaller elements, until the smallest element is at the end. This descending order sorting is critical for various applications where higher values need immediate prominence.
For example, given an array [64, 34, 25, 12, 22, 11, 90], the goal is to transform it into [90, 64, 34, 25, 22, 12, 11].
Example
Consider the input array: [5, 1, 4, 2, 8]
After applying a descending bubble sort, the output will be: [8, 5, 4, 2, 1]
Background & Knowledge Prerequisites
To understand and implement bubble sort in C, you should be familiar with:
- C Language Basics: Fundamental syntax, data types (especially
intfor numbers), and basic program structure. - Arrays: Declaring, initializing, and accessing elements within an array.
- Loops:
forloops are crucial for iterating through array elements multiple times. - Conditional Statements:
ifstatements are used for comparing elements and deciding whether to swap them. - Standard Input/Output: Using
for printing results to the console.
Use Cases
Sorting data in descending order is useful in many real-world scenarios:
- Leaderboards: Displaying game scores or competition results from highest to lowest.
- E-commerce Product Listings: Showing products by price (highest to lowest), popularity, or rating.
- Financial Reports: Listing transactions or stock performance with the highest values first.
- Statistical Analysis: Arranging data points to quickly identify top performers or significant outliers.
- Recent Activity Feeds: Ordering events or news articles from the newest to the oldest (assuming newer has a higher value or timestamp).
Solution Approaches
Bubble Sort for Descending Order
Bubble Sort is a simple comparison-based sorting algorithm. It 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 current element is *smaller* than the next, ensuring larger elements "bubble" towards the beginning of the array.
// Bubble Sort in Descending Order
#include <stdio.h>
void bubbleSortDescending(int arr[], int n) {
int i, j, temp;
// Outer loop for passes (n-1 passes)
for (i = 0; i < n - 1; i++) {
// Inner loop for comparisons in each pass
// The last i elements are already in place
for (j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
// For descending order, if current is smaller than next, swap them
// to move the larger element towards the left (beginning)
if (arr[j] < arr[j+1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
// Function to print an array
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
}
int main() {
// Step 1: Initialize an array
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
// Step 2: Print original array
printf("Original array: ");
printArray(arr, n);
// Step 3: Call bubble sort function to sort in descending order
bubbleSortDescending(arr, n);
// Step 4: Print sorted array
printf("Sorted array (Descending): ");
printArray(arr, n);
return 0;
}
Sample Output
Original array: 64 34 25 12 22 11 90
Sorted array (Descending): 90 64 34 25 22 12 11
Stepwise Explanation
bubbleSortDescending(int arr[], int n)function: This function takes an integer arrayarrand its sizenas input.- Outer Loop (
for (i = 0; i < n - 1; i++)): This loop controls the number of passes through the array. In each pass, at least one element bubbles to its correct position. We needn-1passes because aftern-1passes, the firstn-1elements are sorted, implicitly sorting the last element. - Inner Loop (
for (j = 0; j < n - i - 1; j++)): This loop iterates through the unsorted portion of the array. In each passi, the largestielements are already in their correct descending positions at the beginning of the array. So, we only need to compare up ton - i - 1. - Comparison (
if (arr[j] < arr[j+1])): This is the core logic for descending order. If the current elementarr[j]is *smaller* than the next elementarr[j+1], it means they are in the wrong order for a descending sort. - Swap: If the condition
arr[j] < arr[j+1]is true, the elements are swapped. A temporary variabletempis used to holdarr[j], thenarr[j]takes the value ofarr[j+1], and finally,arr[j+1]takes the value stored intemp. This moves the larger element to the left. printArrayfunction: A helper function to display the contents of the array before and after sorting for verification.mainfunction:
- An example integer array
arris initialized. - The size
nof the array is calculated usingsizeof. - The original array is printed.
-
bubbleSortDescendingis called to sort the array. - The sorted array is printed.
Conclusion
Bubble Sort provides a straightforward method for sorting arrays, including arranging elements in descending order. While its simplicity makes it easy to understand and implement, its efficiency (O(n²) time complexity) means it is generally more suitable for small datasets or educational purposes rather than large-scale, performance-critical applications. Understanding its mechanism is fundamental for grasping more advanced sorting algorithms.
Summary
- Purpose: Arrange elements in an array from largest to smallest.
- Mechanism: Repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong descending order.
- Descending Logic: Swap
arr[j]andarr[j+1]ifarr[j] < arr[j+1], moving the larger element to the left. - Efficiency: Has a time complexity of O(n²) in the worst and average cases, making it less efficient for large datasets compared to algorithms like Merge Sort or Quick Sort.
- Simplicity: Easy to understand and implement, making it a good starting point for learning sorting algorithms.