C Program For Bubble Sort Using Function
Sorting data is a fundamental operation in computer science, crucial for organizing information efficiently. In this article, you will learn how to implement the Bubble Sort algorithm in C, specifically by encapsulating the sorting logic within a reusable function.
Problem Statement
The core problem is to arrange a list of elements (typically numbers) in a specific order, such as ascending or descending. For instance, given an unsorted array of integers [5, 1, 4, 2, 8], we need an algorithm to transform it into [1, 2, 4, 5, 8]. While various sorting algorithms exist, Bubble Sort offers a straightforward, intuitive approach for smaller datasets or educational purposes.
Example
Consider the following array of numbers:
Unsorted Array: [64, 34, 25, 12, 22, 11, 90]
The goal of sorting is to rearrange these numbers into an ordered sequence:
Sorted Array (Ascending): [11, 12, 22, 25, 34, 64, 90]
Background & Knowledge Prerequisites
To understand and implement Bubble Sort using a function in C, you should be familiar with:
- C Language Basics: Variables, data types, and operators.
- Arrays: Declaring, initializing, and accessing elements of an array.
- Loops:
forloops for iteration. - Functions: Defining, calling, and passing arrays to functions.
Relevant setup information: You only need a standard C compiler (like GCC) to compile and run the code.
Use Cases or Case Studies
While not the most efficient for large datasets, Bubble Sort (or simple sorting logic) can be relevant in various contexts:
- Educational Demonstrations: It's an excellent algorithm for teaching basic sorting concepts due to its simplicity.
- Small Data Sorting: For very small arrays where performance isn't critical, its simplicity can outweigh its inefficiency.
- Nearly Sorted Data: If an array is almost sorted, Bubble Sort can perform relatively well in some cases, requiring fewer passes.
- Interactive Visualizations: Its step-by-step swapping process makes it ideal for visual explanations of how sorting algorithms work.
- Embedded Systems (Limited Resources): In systems with extremely limited memory where complex algorithms are difficult to implement, a simple algorithm might be chosen.
Solution Approaches
We will focus on implementing Bubble Sort using a dedicated function to make the code modular and reusable.
Bubble Sort using a Function
This approach defines a separate function responsible for performing the bubble sort operation on an array, enhancing code organization and reusability.
// Bubble Sort using Function
#include <stdio.h>
// Function to perform Bubble Sort
void bubbleSort(int arr[], int n) {
// Step 1: Outer loop for passes (n-1 passes)
for (int i = 0; i < n - 1; i++) {
// Step 2: Inner loop for comparisons and swaps in each pass
for (int j = 0; j < n - i - 1; j++) {
// Step 3: Compare adjacent elements
if (arr[j] > arr[j + 1]) {
// Step 4: Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to print an array
void printArray(int arr[], int size) {
// Step 1: Iterate through the array
for (int i = 0; i < size; i++) {
// Step 2: Print each element
printf("%d ", arr[i]);
}
printf("\\n");
}
int main() {
// Step 1: Define an unsorted array
int arr[] = {64, 34, 25, 12, 22, 11, 90};
// Step 2: Calculate the size of the array
int n = sizeof(arr) / sizeof(arr[0]);
// Step 3: Print the original array
printf("Original array: ");
printArray(arr, n);
// Step 4: Call the bubbleSort function to sort the array
bubbleSort(arr, n);
// Step 5: Print the sorted array
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Sample Output
Original array: 64 34 25 12 22 11 90
Sorted array: 11 12 22 25 34 64 90
Stepwise Explanation
bubbleSortFunction Definition:
- The
bubbleSortfunction takes an integer array (arr[]) and its size (n) as parameters. - It uses two nested
forloops.
- Outer Loop (
i):
- This loop controls the number of passes through the array. For an array of
nelements,n-1passes are sufficient. - In each pass, at least one element "bubbles up" to its correct sorted position.
- Inner Loop (
j):
- This loop performs the comparisons and swaps within each pass.
-
n - i - 1is used as the upper bound because with each passi, the largestielements are already in their correct final positions at the end of the array, so we don't need to re-check them.
- Comparison and Swap:
- Inside the inner loop,
if (arr[j] > arr[j + 1])compares adjacent elements. - If an element is greater than its right neighbor (for ascending sort), they are swapped using a temporary variable
temp.
printArrayFunction:
- A helper function
printArrayis defined to display the contents of an array, making it easy to see the array's state before and after sorting.
mainFunction:
- An unsorted integer array
arris initialized. - Its size
nis calculated. - The original array is printed.
- The
bubbleSortfunction is called, passing the array and its size. Since arrays in C are passed by reference, thebubbleSortfunction modifies the original array directly. - The sorted array is then printed.
Conclusion
Implementing Bubble Sort using a function in C provides a clear and modular way to sort arrays. This approach demonstrates how functions can encapsulate specific logic, making your code easier to read, maintain, and reuse. While Bubble Sort is simple to understand, its efficiency (O(n²) time complexity) means it's generally better suited for small datasets or as an educational tool.
Summary
- Bubble Sort Concept: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.
- Function Encapsulation: Using a
bubbleSortfunction improves code organization and reusability. - Parameters: The function takes the array and its size as arguments.
- Swapping Logic: A temporary variable is used to swap elements that are out of order.
- Efficiency: Bubble Sort 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.
- Educational Value: Excellent for understanding basic sorting principles due to its straightforward implementation.