1. Introduction
Sorting is a ubiquitous operation in computing. While arranging data in ascending order is more common, there are use cases where data needs to be sorted in descending order. For instance, when ranking scores in a game or sorting top-rated products. In this guide, we'll walk you through a C program that sorts an array in descending order using the Bubble Sort algorithm.
2. Program Overview
The program will:
1. Request the user to enter the number of elements and the array of elements.
2. Implement the Bubble Sort algorithm to sort the array elements in descending order.
3. Display the sorted array to the user.
3. Code Program
#include <stdio.h> // Include the standard I/O library.
int main() { // Begin the main function.
int n, i, j, temp; // Declare the number of elements (n), loop counters (i, j), and a temporary variable for swapping (temp).
printf("Enter number of elements: "); // Ask the user for the number of elements.
scanf("%d", &n); // Read the number of elements.
int arr[n]; // Declare an array of size 'n'.
printf("Enter %d integers: ", n); // Ask the user for the array elements.
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Read each array element and store it.
}
// Implementing Bubble Sort for descending order.
for(i = 0; i < n - 1; i++) {
for(j = 0; j < n - 1 - i; j++) {
if(arr[j] < arr[j + 1]) { // Compare adjacent elements.
// Swap arr[j] and arr[j+1] if arr[j] is less than arr[j+1].
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted array in descending order:\n");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]); // Display each element of the sorted array.
}
return 0; // End the program.
}
Output:
Enter number of elements: 5 Enter 5 integers: 64 34 25 12 22 Sorted array in descending order: 64 34 25 22 12
4. Step By Step Explanation
1. Header Inclusion: We include the standard I/O library to facilitate input-output operations.
2. Main Function: This is the entry point of our program.
3. Variable Declaration:
- n is used to store the number of elements.
- i and j are loop counters.
- temp is for swapping values.
4. Taking User Input:
- We ask and then read the number of elements the user wants to sort.
- We then take each of those elements as input.
5. Bubble Sort (Descending):
- Unlike the typical Bubble Sort that arranges elements in ascending order, here we slightly modify the condition to sort in descending order.
- During each pass, if an element is less than its adjacent element, they are swapped.
- The outer loop ensures we go through every element, and the inner loop facilitates the actual comparison and swapping.
6. Output the Result: After sorting, we display the sorted array in descending order.
This Bubble Sort method, although intuitive and simple, is not the most efficient for large datasets. It's still quite illustrative for new learners and helps in understanding basic algorithmic concepts.
Comments
Post a Comment
Leave Comment