C++ Program For Bubble Sort Without Using Function
Bubble Sort is a straightforward comparison-based sorting algorithm. In this article, you will learn how to implement the Bubble Sort algorithm in C++ directly within the main function, without using any custom helper functions.
Problem Statement
Sorting data is a fundamental task in computer science, crucial for efficiently organizing and processing information. Imagine having a list of unsorted numbers; without a method to arrange them, finding specific values or understanding patterns becomes difficult. The problem is to arrange a given array of elements into ascending or descending order using the Bubble Sort algorithm.
Example
Consider an unsorted array of integers: [64, 34, 25, 12, 22, 11, 90]
After applying Bubble Sort, the array will be sorted in ascending order: [11, 12, 22, 25, 34, 64, 90]
Background & Knowledge Prerequisites
To understand and implement Bubble Sort, readers should be familiar with:
- C++ Basics: Fundamental syntax, variable declaration, and data types.
- Arrays: How to declare, initialize, and access elements in a one-dimensional array.
- Loops:
forloops for iterating through arrays. - Conditional Statements:
ifstatements for comparison logic. - Swapping Variables: The concept of exchanging values between two variables.
Use Cases or Case Studies
While not the most efficient for large datasets, Bubble Sort is useful for:
- Educational Purposes: It's often the first sorting algorithm taught due to its simplicity, making it excellent for understanding basic sorting logic.
- Small Datasets: For very small arrays (e.g., fewer than 10-20 elements), its simplicity might outweigh the performance cost.
- Nearly Sorted Data: If an array is almost sorted, Bubble Sort can perform relatively quickly as it will only require a few passes.
- Visualizations: Its step-by-step comparison and swapping process makes it easy to visualize how a sort works.
Solution Approaches
For this specific requirement, we will focus on one direct approach: implementing Bubble Sort entirely within the main function to avoid using separate helper functions.
Bubble Sort Implementation in main()
One-line summary: Directly implement the Bubble Sort algorithm, including nested loops and swapping logic, within the main function of a C++ program.
// Bubble Sort without function
#include <iostream> // Required for input/output operations
int main() {
// Step 1: Declare and initialize an unsorted 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
std::cout << "Original array: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// Step 3: Implement Bubble Sort using nested loops
// 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
for (int j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
if (arr[j] > arr[j + 1]) {
// If the current element is greater than the next, swap them
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Step 4: Print the sorted array
std::cout << "Sorted array (ascending): ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0; // Indicate successful execution
}
Sample output:
Original array: 64 34 25 12 22 11 90
Sorted array (ascending): 11 12 22 25 34 64 90
Stepwise explanation:
- Include Header: The
iostreamheader is included to enable standard input and output operations, such as printing to the console. - Array Initialization: An integer array
arris declared and initialized with unsorted values. Thenvariable calculates the total number of elements in the array. - Original Array Output: A
forloop iterates through the array and prints its elements, showing the unsorted state. - Outer Loop (Passes): The first
forloop runsn-1times. Each iteration of this loop represents a "pass" through the array. In each pass, at least one element "bubbles up" to its correct sorted position. - Inner Loop (Comparisons and Swaps): The second, nested
forloop iterates through the unsorted portion of the array.
- It compares adjacent elements (
arr[j]andarr[j+1]). - If
arr[j]is greater thanarr[j+1], their values are swapped. This is done using a temporary variabletempto hold one value while the swap occurs. - The
n - i - 1in the inner loop's condition ensures that comparisons stop at the last unsorted element, as elements at the end become sorted with each outer pass.
- Sorted Array Output: After the nested loops complete, the array
arrwill be fully sorted in ascending order. Anotherforloop prints the elements of the now-sorted array. - Return 0: The
mainfunction returns0to signify successful program execution.
Conclusion
Implementing Bubble Sort without using separate functions is straightforward, particularly for understanding its core logic. By nesting two for loops and performing conditional swaps within main, we can effectively sort an array. This approach highlights the algorithm's simplicity and direct application of array and loop fundamentals.
Summary
- Bubble Sort sorts an array by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order.
- The implementation involves nested
forloops: an outer loop for passes and an inner loop for comparisons and swaps. - A temporary variable is crucial for correctly swapping elements.
- While simple to understand and implement, Bubble Sort is generally inefficient for large datasets.