📘 Lesson · Lesson 77
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
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.