C Program Of Simple Bubble Sort Implementation Using Array Ascending Order
Bubble sort is a fundamental sorting algorithm that arranges elements of an array in a specific order. In this article, you will learn how to implement a simple bubble sort program in C to sort an array of integers in ascending order.
Problem Statement
The core problem is to efficiently arrange a given list of unsorted numbers, stored in an array, into an ascending sequence. This is a common requirement in various data processing tasks, from organizing search results to preparing data for further analysis. For instance, if you have a list of student scores [64, 25, 12, 22, 11], the goal is to transform it into [11, 12, 22, 25, 64].
Example
Consider an unsorted array of integers: [5, 1, 4, 2, 8]
After applying the bubble sort algorithm in ascending order, the array will become: [1, 2, 4, 5, 8]
Background & Knowledge Prerequisites
To understand and implement bubble sort in C, readers should be familiar with the following basic C programming concepts:
- Variables and Data Types: Understanding
intfor integer numbers. - Arrays: How to declare, initialize, and access elements in a one-dimensional array.
- Loops: Proficient use of
forloops for iteration. - Conditional Statements: Using
ifstatements for comparisons. - Function Basics: Understanding
mainfunction andprintffor output.
Use Cases or Case Studies
Sorting algorithms, including bubble sort, are foundational in computer science and have numerous applications:
- Educational Purposes: Bubble sort is often taught as an introductory sorting algorithm due to its simplicity, making it easy to understand the concept of comparisons and swaps.
- Small Data Sets: For very small arrays (e.g., less than 10-20 elements), the performance difference between bubble sort and more complex algorithms is negligible, making its simplicity appealing.
- Nearly Sorted Data: If an array is already mostly sorted, bubble sort can perform relatively well as it only needs a few passes to "bubble" the out-of-place elements to their correct positions.
- Interactive Visualizations: Its step-by-step comparisons and swaps make it an excellent candidate for visualizing how sorting algorithms work, helping learners grasp the process.
- Simple Utility Functions: In embedded systems or specific scenarios where code size and simplicity are prioritized over raw performance for small data, bubble sort might be a quick-to-implement solution.
Solution Approaches
Simple Bubble Sort Implementation
Bubble sort works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. This process is repeated until no swaps are needed, indicating the list is sorted. Each pass effectively "bubbles" the largest unsorted element to its correct position at the end of the unsorted portion.
// Bubble Sort in Ascending Order
#include <stdio.h>
void bubbleSort(int arr[], int n) {
// Outer loop for passes through the array
for (int i = 0; i < n - 1; i++) {
// Inner loop for comparisons and swaps in each pass
for (int j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
// If the element on the left is greater than the element on the right, swap them
if (arr[j] > arr[j + 1]) {
// Perform swap using a temporary variable
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
}
int main() {
// Step 1: Initialize an unsorted array
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
printf("Original array: \\n");
printArray(arr, n);
// Step 2: Call the bubbleSort function to sort the array
bubbleSort(arr, n);
printf("Sorted array in ascending order: \\n");
printArray(arr, n);
return 0;
}
Sample Output:
Original array:
64 34 25 12 22 11 90
Sorted array in ascending order:
11 12 22 25 34 64 90
Stepwise Explanation:
bubbleSortFunction Definition:
- It takes an integer array
arrand its sizenas input.
- Outer Loop (
for (int i = 0; i < n - 1; i++)):
- This loop controls the number of passes through the array. For an array of
nelements,n-1passes are sufficient. - In each pass
i, the largest unsorted element "bubbles" to its correct position at the end of the unsorted portion of the array.
- Inner Loop (
for (int j = 0; j < n - i - 1; j++)):
- This loop iterates through the unsorted part of the array in each pass.
- The
n - i - 1ensures that we don't compare elements that are already sorted (at the end of the array due to previous passes) and also prevents out-of-bounds access.
- Comparison and Swap (
if (arr[j] > arr[j + 1])):
- Inside the inner loop, adjacent elements
arr[j]andarr[j + 1]are compared. - If
arr[j]is greater thanarr[j + 1](meaning they are in the wrong order for ascending sort), their values are swapped. - A temporary variable
tempis used to facilitate this swap.
printArrayFunction:
- A helper function to display the contents of the array, making it easy to see the original and sorted states.
mainFunction:
- An example array
arris initialized. - The size
nis calculated. - The original array is printed.
- The
bubbleSortfunction is called to sort the array. - The sorted array is then printed.
Conclusion
Bubble sort is a straightforward sorting algorithm well-suited for teaching and understanding fundamental sorting concepts. While it is simple to implement, its time complexity (O(n^2) in the worst and average cases) makes it inefficient for large datasets compared to more advanced algorithms like quicksort or mergesort. However, for small arrays or educational purposes, it remains a valuable tool for demonstrating how elements can be arranged systematically.
Summary
- Bubble sort arranges elements by repeatedly comparing and swapping adjacent elements.
- It's simple to implement and easy to understand.
- The algorithm makes multiple passes through the array until no more swaps are needed.
- It has a time complexity of O(n^2), making it less efficient for large arrays.
- Ideal for small datasets, educational demonstrations, and cases where simplicity is prioritized.