Sort the array into descending order.
Learn how to implement Bubble Sort for descending order in C
๐งพ Step-by-Step Explanation
๐น Step 1: Include Header File
#include <stdio.h>
This standard library provides essential functions:
printf()
for displaying outputscanf()
for reading user input- Basic console I/O operations
๐น Step 2: Declare Variables and Array
int arr[100], n, i, j, temp;
- arr[100]: Array that can hold up to 100 integers
- n: Actual number of elements to be sorted
- i, j: Loop counters for sorting passes
- temp: Temporary variable for element swapping
๐น Step 3: Input Size and Elements
printf("Enter the number of elements: ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
- First gets the array size (n ≤ 100)
- Then collects each element from user
- Stores elements in sequential array positions
- Displays index with each input prompt
๐น Step 4: Sort the Array (Bubble Sort - Descending)
for(i = 0; i < n - 1; i++) {
for(j = 0; j < n - i - 1; j++) {
if(arr[j] < arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
Modified Bubble Sort for descending order:
- Outer loop: Controls number of passes (n-1 passes needed)
- Inner loop: Compares adjacent elements in each pass
- Comparison: Checks if left element is smaller than right
- Swapping: Exchanges elements if in wrong order
- With each pass, smallest unsorted element "bubbles down"
๐น Step 5: Display Sorted Array
for(i = 0; i < n; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
- Prints all elements in sorted descending order
- Shows both index and value for each element
- Verifies the successful sorting
- Uses newline character for clean output
๐งช Sample Output
Enter the number of elements: 5
Enter 5 elements:
arr[0]: 25
arr[1]: 40
arr[2]: 10
arr[3]: 60
arr[4]: 30
Array in descending order:
arr[0] = 60
arr[1] = 40
arr[2] = 30
arr[3] = 25
arr[4] = 10
๐ Key Concepts Covered
Bubble Sort Algorithm
A simple comparison-based sorting method with O(n²) time complexity, modified for descending order
Descending Order
Arranging elements from largest to smallest value
Array Processing
Storing and manipulating multiple values in a linear data structure
Element Swapping
Using a temporary variable to exchange two array values
Nested Loop Control
Outer loop for passes; inner loop for element comparison and swapping
No comments:
Post a Comment