📘 Lesson · Lesson 77
Bubble Sort
Bubble Sort
Bubble Sort
💡 Note
Bubble sort repeatedly swaps adjacent out-of-order elements until the array is sorted.
Program
C++
#include <iostream>
using namespace std;
int main() {
int a[] = {5, 2, 8, 1, 9}, n = 5;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (a[j] > a[j+1]) swap(a[j], a[j+1]);
for (int x : a) cout << x << " "; // 1 2 5 8 9
return 0;
}Output:
1 2 5 8 9
1 2 5 8 9
Summary
- Compare neighbours and swap; largest "bubbles" to the end each pass.
- Time complexity O(n^2).
Bubble Sort
💡 Note
Bubble sort बार-बार adjacent गलत-क्रम elements swap करता है जब तक array sorted न हो।
Program
C++
#include <iostream>
using namespace std;
int main() {
int a[] = {5, 2, 8, 1, 9}, n = 5;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (a[j] > a[j+1]) swap(a[j], a[j+1]);
for (int x : a) cout << x << " "; // 1 2 5 8 9
return 0;
}Output:
1 2 5 8 9
1 2 5 8 9
सारांश
- Neighbours compare करके swap करें; हर pass में सबसे बड़ा अंत तक "bubble" होता है।
- Time complexity O(n^2)।