C Program For Bubble Sort Without Using Function
Sorting an array is a fundamental operation in computer science, used across various applications. While C offers powerful ways to modularize code with functions, understanding how to implement algorithms directly within the main function is crucial for grasping core concepts. In this article, you will learn how to implement the bubble sort algorithm in C without using any separate functions.
Problem Statement
The problem is to arrange a given list of elements (an array) in a specific order, typically ascending or descending. For example, transforming an unsorted array like [5, 1, 4, 2, 8] into a sorted array [1, 2, 4, 5, 8]. Efficiently sorting data is vital for tasks like searching, database management, and data analysis, making this a cornerstone problem in programming.
Example
Consider the following unsorted array: [64, 34, 25, 12, 22, 11, 90]
After applying the bubble sort algorithm, the array will be sorted in ascending order: [11, 12, 22, 25, 34, 64, 90]
Background & Knowledge Prerequisites
To understand this implementation, readers should be familiar with:
- C basics: Variables, data types (especially
intfor integers). - Arrays: Declaring, initializing, and accessing elements.
- Loops:
forloops for iteration. - Conditional statements:
ifstatements for comparisons.
Use Cases or Case Studies
Sorting algorithms, including the concept behind bubble sort, are foundational to many real-world scenarios:
- Organizing lists: Alphabetizing names, sorting products by price, or ordering search results by relevance.
- Database indexing: Efficiently retrieving data from large datasets.
- Data visualization: Presenting data in a meaningful, ordered way (e.g., bar charts, trend lines).
- Search algorithms: Many advanced search techniques require data to be sorted first to work efficiently.
- Ranking systems: Displaying leaderboards or top performers in applications.
Solution Approaches
For this specific requirement, we will focus on one direct approach to implement bubble sort entirely within the main function.
Bubble Sort Implementation (Without Functions)
This approach sorts an array by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. The pass-through is repeated until no swaps are needed, indicating that the list is sorted.
// Bubble Sort without Function
#include <stdio.h>
int main() {
// Step 1: Declare and initialize the array
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements
// Step 2: Print the original array
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
// Step 3: Implement Bubble Sort algorithm
// Outer loop for passes (n-1 passes are sufficient)
for (int i = 0; i < n - 1; i++) {
// Inner loop for comparisons and swaps in each pass
// The last i elements are already in place, so we don't need to check them
for (int j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
if (arr[j] > arr[j + 1]) {
// Swap if the element found is greater than the next element
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Step 4: Print the sorted array
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\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
- Array Initialization: An integer array
arris declared and initialized with unsorted values. The variablencalculates the total number of elements in the array. - Original Array Display: A
forloop iterates through thearrand prints its initial, unsorted state to the console. - Outer Loop (
i): This loop controls the number of passes through the array. For an array ofnelements,n-1passes are generally sufficient because in each pass, at least one element "bubbles" to its correct position (the largest unsorted element moves to the end of the unsorted portion). - Inner Loop (
j): This loop performs the comparisons and swaps within each pass. It iterates from the beginning of the array up to then-i-1th element. Then-i-1part is crucial because afteripasses, the lastielements are already in their correct sorted positions, so they don't need to be re-checked. - Comparison and Swap: Inside the inner loop,
if (arr[j] > arr[j + 1])compares an element with its adjacent element. If the current element (arr[j]) is greater than the next element (arr[j+1]), their positions are swapped using a temporary variabletemp. This moves the larger element to the right. - Sorted Array Display: After the nested loops complete, the array is sorted. A final
forloop prints the elements of the now sorted array.
Conclusion
Implementing bubble sort without using separate functions directly within the main function provides a clear, self-contained demonstration of how this basic sorting algorithm works. By understanding the roles of the nested loops and the comparison-and-swap logic, you can grasp the core mechanics of how elements are moved into their sorted positions. While bubble sort is not the most efficient algorithm for large datasets, its simplicity makes it an excellent starting point for learning about sorting.
Summary
- Bubble sort is a simple sorting algorithm that repeatedly steps through the list.
- It compares adjacent elements and swaps them if they are in the wrong order.
- The process continues until no swaps are needed, indicating a sorted list.
- The implementation uses nested
forloops entirely withinmainto achieve sorting without separate functions. - The outer loop controls passes, and the inner loop handles comparisons and swaps.