📘 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 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
सारांश
- Compare neighbours and swap; largest "bubbles" to the end each pass.
- Time complexity O(n^2).
💻 Live Code Editor
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.