1. Introduction
Bubble Sort is a straightforward sorting algorithm that repeatedly traverses the list, compares adjacent elements, and swaps them if they are in the incorrect sequence. The process is iterated until the list is fully sorted. In this guide, we will focus on sorting a list in descending order using Bubble Sort.
2. Program Overview
This program is organized into the following sections:
1. swap: A utility function to interchange the positions of two integers.
2. bubbleSort: The primary function that implements Bubble Sort in descending order.
3. printArray: A helper function to display the array's contents.
4. main: The main function where the program execution begins.
3. Code Program
#include <stdio.h>
// A utility function to swap two integers
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// Implementation of bubbleSort to sort in descending order
void bubbleSort(int arr[], int n) {
int i, j;
// Outer loop for the number of passes
for (i = 0; i < n-1; i++) {
// Inner loop for each pass
for (j = 0; j < n-i-1; j++) {
// If current element is smaller than the next element, swap them
if (arr[j] < arr[j+1]) {
swap(&arr[j], &arr[j+1]);
}
}
}
}
// Function to print the array
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Main function to test the bubbleSort function
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array in descending order: \n");
printArray(arr, n);
return 0;
}
Output:
Sorted array in descending order: 90 64 34 25 22 12 11
4. Step By Step Explanation
The bubbleSort function works as follows:
1. The outer loop runs n-1 times, where n is the number of elements in the array. Each iteration of this loop represents a pass through the array.
2. The inner loop performs the actual comparison and swapping of elements for each pass. With each pass, the biggest element bubbles up to its correct position at the start of the array.
3. The inner loop's condition is arr[j] < arr[j+1] because we want to sort in descending order. When the current element is smaller than the next element, we swap them.
4. With every iteration of the outer loop, one fewer elements are considered in the inner loop since the biggest elements are already in their final sorted positions.
5. Once all passes are completed, the array is sorted in descending order.
Related C Programs on Sorting Algorithms
- Bubble Sort in Ascending Order in C
- Bubble Sort in Descending Order in C
- Selection Sort in Ascending Order in C
- Selection Sort in Descending Order in C
- Insertion Sort in Ascending Order in C
- Insertion Sort in Descending Order in C
- Merge Sort in Ascending Order in C
- Merge Sort in Descending Order in C
- Quick Sort in Ascending Order in C
- Quick Sort in Descending Order in C
- Heap Sort in Ascending Order in C
- Heap Sort in Descending Order in C
Comments
Post a Comment