📘 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

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

सारांश

  • Neighbours compare करके swap करें; हर pass में सबसे बड़ा अंत तक "bubble" होता है।
  • Time complexity O(n^2)।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n