Table of contents | |
Understanding Bubble Sort | |
Bubble Sort Algorithm | |
Bubble Sort Code in C++ | |
Conclusion |
Sorting is a fundamental operation in computer programming, and one of the simplest sorting algorithms is Bubble Sort. Bubble Sort is easy to understand and implement, making it an excellent starting point for beginners learning sorting algorithms in C++. In this article, we'll explore Bubble Sort in detail, along with multiple examples and code explanations.
Bubble Sort is a comparison-based sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted. The name "Bubble Sort" comes from the way smaller elements "bubble" to the top of the list during each pass.
Here's a step-by-step breakdown of the Bubble Sort algorithm:
Now let's dive into some example code to see how Bubble Sort works in practice.
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 2, 8, 12, 3};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
bubbleSort(arr, size);
cout << "\nSorted array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
Let's see the output of the above code:
Original array: 5 2 8 12 3
Sorted array: 2 3 5 8 12
As you can see, the Bubble Sort algorithm successfully sorted the array in ascending order.
Bubble Sort is a simple yet effective sorting algorithm that can be easily understood and implemented by beginners. It serves as a great starting point for learning about sorting algorithms in C++. By grasping the concepts and examining the code examples in this article, you should now have a solid understanding of how Bubble Sort works.
70 videos|45 docs|15 tests
|
|
Explore Courses for Software Development exam
|